feat: enhance product metadata handling with category, group, and brand summaries

This commit is contained in:
BXY 2026-10-26 11:14:47 +08:00
parent 7ce922d440
commit 47539d663d
5 changed files with 333 additions and 3 deletions

View File

@ -123,7 +123,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。
返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。该接口额外批量回填每个商品直接绑定的标准类目(含直属父节点和根至当前节点完整路径)、商品分组及当前可用品牌展示信息;无类目/分组时返回空数组,无品牌时返回空值。`ListCategoryProducts` 和 `SearchProducts` 不填充这些后台列表展示字段。
### `ListCategoryProducts`

View File

@ -373,7 +373,25 @@ func catalogWhere(scope StoreScope, query string, statusValue *int32, supplierID
where := ` WHERE tenant_id=$1 AND store_id=$2 AND deleted_at IS NULL`
if strings.TrimSpace(query) != "" {
args = append(args, "%"+strings.TrimSpace(query)+"%")
where += fmt.Sprintf(" AND (name ILIKE $%d OR alias ILIKE $%d OR %s ILIKE $%d)", len(args), len(args), map[bool]string{true: "brand_code", false: "supplier_code"}[isBrand], len(args))
queryPosition := len(args)
if isBrand {
where += fmt.Sprintf(" AND (name ILIKE $%d OR alias ILIKE $%d OR brand_code ILIKE $%d)", queryPosition, queryPosition, queryPosition)
} else {
where += fmt.Sprintf(` AND (
name ILIKE $%d
OR alias ILIKE $%d
OR supplier_code ILIKE $%d
OR EXISTS (
SELECT 1
FROM product.brands b
WHERE b.supplier_id = product.suppliers.id
AND b.tenant_id = product.suppliers.tenant_id
AND b.store_id = product.suppliers.store_id
AND b.deleted_at IS NULL
AND (b.name ILIKE $%d OR b.alias ILIKE $%d OR b.brand_code ILIKE $%d)
)
)`, queryPosition, queryPosition, queryPosition, queryPosition, queryPosition, queryPosition)
}
}
if statusValue != nil {
args = append(args, *statusValue)

View File

@ -0,0 +1,34 @@
package repository
import (
"strings"
"testing"
)
func TestCatalogWhereSupplierQueryIncludesBrandFieldsWithoutJoin(t *testing.T) {
where, args := catalogWhere(StoreScope{TenantID: 10, StoreID: 20}, "QF", nil, "", false)
if len(args) != 3 || args[2] != "%QF%" {
t.Fatalf("catalogWhere() args = %#v, want tenant, store, keyword", args)
}
for _, fragment := range []string{
"EXISTS", "FROM product.brands b", "b.name ILIKE $3", "b.alias ILIKE $3", "b.brand_code ILIKE $3",
} {
if !strings.Contains(where, fragment) {
t.Errorf("catalogWhere() missing %q in %s", fragment, where)
}
}
if strings.Contains(where, "JOIN product.brands") {
t.Fatalf("catalogWhere() must use EXISTS to avoid duplicate suppliers: %s", where)
}
}
func TestCatalogWhereBrandQueryDoesNotAddSupplierBrandExists(t *testing.T) {
where, _ := catalogWhere(StoreScope{TenantID: 10, StoreID: 20}, "QF", nil, "", true)
if strings.Contains(where, "EXISTS") {
t.Fatalf("brand list query must not add supplier-brand EXISTS predicate: %s", where)
}
if !strings.Contains(where, "brand_code ILIKE $3") {
t.Fatalf("brand list query missing brand code predicate: %s", where)
}
}

View File

@ -300,10 +300,47 @@ type CategoryProductRecord struct {
LockedQuantity int64
CategoryPropertiesJSON string
PresaleType int32
ProductCategories []ProductCategorySummaryRecord
Groups []ProductGroupSummaryRecord
Brand *ProductBrandSummaryRecord
CreatedAt time.Time
UpdatedAt time.Time
}
// ProductCategoryPathNodeRecord is one root-to-leaf node in a standard
// product-category path.
type ProductCategoryPathNodeRecord struct {
ID string
Name string
Level int32
ParentID *string
}
// ProductCategorySummaryRecord describes one standard category directly bound
// to a product, along with its immediate parent and complete ancestor path.
type ProductCategorySummaryRecord struct {
ID string
Name string
Level int32
ParentID *string
ParentName string
Path []ProductCategoryPathNodeRecord
}
// ProductGroupSummaryRecord describes one product-group binding.
type ProductGroupSummaryRecord struct {
ID string
Name string
}
// ProductBrandSummaryRecord is the display projection of a product brand.
type ProductBrandSummaryRecord struct {
ID string
Name string
Alias string
BrandCode string
}
// ProductListFilter contains the optional constraints for an admin product list.
type ProductListFilter struct {
CreatedAtFrom *time.Time
@ -3397,9 +3434,222 @@ LIMIT $`+strconv.Itoa(limitArg)+` OFFSET $`+strconv.Itoa(offsetArg), queryArgs..
if err := rows.Err(); err != nil {
return nil, 0, fmt.Errorf("iterate products: %w", err)
}
if err := r.populateProductListMetadata(ctx, products, scope); err != nil {
return nil, 0, err
}
return products, total, nil
}
// populateProductListMetadata loads list-only display projections in batches so
// product pagination never causes one query per product.
func (r *ProductRepository) populateProductListMetadata(ctx context.Context, products []*CategoryProductRecord, scope StoreScope) error {
if len(products) == 0 {
return nil
}
productIDs := make([]int64, 0, len(products))
byID := make(map[string]*CategoryProductRecord, len(products))
for _, product := range products {
if product == nil {
continue
}
id, err := parseID(product.ID, "product_id")
if err != nil {
return err
}
productIDs = append(productIDs, id)
byID[product.ID] = product
product.ProductCategories = []ProductCategorySummaryRecord{}
product.Groups = []ProductGroupSummaryRecord{}
}
if len(productIDs) == 0 {
return nil
}
if err := r.populateProductCategorySummaries(ctx, productIDs, byID, scope); err != nil {
return err
}
if err := r.populateProductGroupSummaries(ctx, productIDs, byID, scope); err != nil {
return err
}
if err := r.populateProductBrandSummaries(ctx, productIDs, byID, scope); err != nil {
return err
}
return nil
}
func nullableFormattedID(value sql.NullInt64) *string {
if !value.Valid {
return nil
}
id := formatID(value.Int64)
return &id
}
func (r *ProductRepository) populateProductCategorySummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error {
placeholders, idArgs := productIDPlaceholders(productIDs, 3)
args := append([]any{scope.TenantID, scope.StoreID}, idArgs...)
rows, err := r.db.QueryContext(ctx, `
WITH RECURSIVE category_paths AS (
SELECT b.product_id,
c.id AS bound_category_id,
c.id,
c.parent_id,
c.name,
c.level,
0 AS depth,
ARRAY[c.id] AS visited_category_ids
FROM product.product_category_bindings b
JOIN product.product_category c ON c.id = b.product_category_id
WHERE b.tenant_id = $1
AND b.store_id = $2
AND b.deleted_at IS NULL
AND c.deleted_at IS NULL
AND b.product_id IN (`+placeholders+`)
UNION ALL
SELECT cp.product_id,
cp.bound_category_id,
parent.id,
parent.parent_id,
parent.name,
parent.level,
cp.depth + 1,
cp.visited_category_ids || parent.id
FROM category_paths cp
JOIN product.product_category parent ON parent.id = cp.parent_id
WHERE parent.deleted_at IS NULL
AND NOT parent.id = ANY(cp.visited_category_ids)
)
SELECT product_id, bound_category_id, id, parent_id, name, level, depth
FROM category_paths
ORDER BY product_id, bound_category_id, depth DESC`, args...)
if err != nil {
return fmt.Errorf("list product category summaries: %w", err)
}
defer rows.Close()
byProductCategory := make(map[string]map[string]*ProductCategorySummaryRecord)
for rows.Next() {
var productID, boundCategoryID, categoryID int64
var parentID sql.NullInt64
var name string
var level, depth int32
if err := rows.Scan(&productID, &boundCategoryID, &categoryID, &parentID, &name, &level, &depth); err != nil {
return fmt.Errorf("scan product category summary: %w", err)
}
productKey, boundKey := formatID(productID), formatID(boundCategoryID)
categoryByProduct := byProductCategory[productKey]
if categoryByProduct == nil {
categoryByProduct = make(map[string]*ProductCategorySummaryRecord)
byProductCategory[productKey] = categoryByProduct
}
summary := categoryByProduct[boundKey]
if summary == nil {
summary = &ProductCategorySummaryRecord{ID: boundKey, Path: []ProductCategoryPathNodeRecord{}}
categoryByProduct[boundKey] = summary
}
if depth == 0 {
summary.Name = name
summary.Level = level
summary.ParentID = nullableFormattedID(parentID)
}
summary.Path = append(summary.Path, ProductCategoryPathNodeRecord{
ID: formatID(categoryID), Name: name, Level: level, ParentID: nullableFormattedID(parentID),
})
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate product category summaries: %w", err)
}
for productID, categories := range byProductCategory {
product := products[productID]
if product == nil {
continue
}
for _, category := range categories {
if category.ParentID != nil {
for _, node := range category.Path {
if node.ID == *category.ParentID {
category.ParentName = node.Name
break
}
}
}
product.ProductCategories = append(product.ProductCategories, *category)
}
sort.Slice(product.ProductCategories, func(i, j int) bool {
left, right := product.ProductCategories[i], product.ProductCategories[j]
if left.Level != right.Level {
return left.Level < right.Level
}
return left.ID < right.ID
})
}
return nil
}
func (r *ProductRepository) populateProductGroupSummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error {
placeholders, idArgs := productIDPlaceholders(productIDs, 2)
args := append([]any{scope.StoreID}, idArgs...)
rows, err := r.db.QueryContext(ctx, `
SELECT b.product_id, c.id, c.name
FROM product.product_catalog_bindings b
JOIN product.catalog_category c ON c.id = b.category_id
WHERE c.store_id = $1
AND c.node_type = 2
AND b.product_id IN (`+placeholders+`)
ORDER BY b.product_id, c.sort_num, c.id`, args...)
if err != nil {
return fmt.Errorf("list product group summaries: %w", err)
}
defer rows.Close()
for rows.Next() {
var productID, groupID int64
var name string
if err := rows.Scan(&productID, &groupID, &name); err != nil {
return fmt.Errorf("scan product group summary: %w", err)
}
if product := products[formatID(productID)]; product != nil {
product.Groups = append(product.Groups, ProductGroupSummaryRecord{ID: formatID(groupID), Name: name})
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate product group summaries: %w", err)
}
return nil
}
func (r *ProductRepository) populateProductBrandSummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error {
placeholders, idArgs := productIDPlaceholders(productIDs, 3)
args := append([]any{scope.TenantID, scope.StoreID}, idArgs...)
rows, err := r.db.QueryContext(ctx, `
SELECT p.id, b.id, b.name, b.alias, b.brand_code
FROM product.products p
JOIN product.brands b ON b.id = p.brand_id
AND b.tenant_id = $1
AND b.store_id = $2
AND b.deleted_at IS NULL
WHERE p.id IN (`+placeholders+`)
AND p.tenant_id = $1
AND p.store_id = $2
AND p.deleted_at IS NULL`, args...)
if err != nil {
return fmt.Errorf("list product brand summaries: %w", err)
}
defer rows.Close()
for rows.Next() {
var productID, brandID int64
var name, alias, brandCode string
if err := rows.Scan(&productID, &brandID, &name, &alias, &brandCode); err != nil {
return fmt.Errorf("scan product brand summary: %w", err)
}
if product := products[formatID(productID)]; product != nil {
product.Brand = &ProductBrandSummaryRecord{ID: formatID(brandID), Name: name, Alias: alias, BrandCode: brandCode}
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate product brand summaries: %w", err)
}
return nil
}
func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any) {
predicates := []string{"p.deleted_at IS NULL", "p.store_id = $1"}
args := []any{scope.StoreID}

View File

@ -2963,7 +2963,7 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv
if product == nil {
return nil
}
return &productv1.CategoryProduct{
result := &productv1.CategoryProduct{
UpdatedAt: timeToMillisString(product.UpdatedAt),
CreatedAt: timeToMillisString(product.CreatedAt),
Title: product.Title,
@ -2978,6 +2978,34 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv
CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON),
PresaleType: product.PresaleType,
}
for _, category := range product.ProductCategories {
item := &productv1.ProductCategorySummary{
ProductCategoryId: category.ID,
Name: category.Name,
Level: category.Level,
ParentCategoryId: category.ParentID,
ParentCategoryName: category.ParentName,
Path: make([]*productv1.ProductCategoryPathNode, 0, len(category.Path)),
}
for _, node := range category.Path {
item.Path = append(item.Path, &productv1.ProductCategoryPathNode{
ProductCategoryId: node.ID,
Name: node.Name,
Level: node.Level,
ParentCategoryId: node.ParentID,
})
}
result.ProductCategories = append(result.ProductCategories, item)
}
for _, group := range product.Groups {
result.Groups = append(result.Groups, &productv1.ProductGroupSummary{GroupId: group.ID, Name: group.Name})
}
if product.Brand != nil {
result.Brand = &productv1.ProductBrandSummary{
BrandId: product.Brand.ID, Name: product.Brand.Name, Alias: product.Brand.Alias, BrandCode: product.Brand.BrandCode,
}
}
return result
}
func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductItemInventory {