feat(product): 聚合分类商品最低价与销量

This commit is contained in:
BXY0414 2026-07-14 18:57:26 +08:00
parent bbe9ee0be2
commit a6bca494f4
3 changed files with 44 additions and 126 deletions

View File

@ -121,6 +121,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| `total` | `int64` | 分类/分组下商品总数 | | `total` | `int64` | 分类/分组下商品总数 |
| `total_pages` | `int32` | 总页数 | | `total_pages` | `int32` | 总页数 |
`products[]` 返回商品摘要以及全部未删除 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。
`products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。 `products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
### `ListCategoryTree` ### `ListCategoryTree`

View File

@ -95,18 +95,12 @@ type CategoryProductRecord struct {
Title string Title string
Status productv1.ProductStatus Status productv1.ProductStatus
ImageIDs []string ImageIDs []string
Price int64
SoldQuantity int64
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
} }
// CategoryProductSKURecord is the SKU summary returned by category product lists.
type CategoryProductSKURecord struct {
ID string
ProductID string
AvailableQuantity int32
Price int64
}
// CategoryRecord is the persistence model for product.product_category. // CategoryRecord is the persistence model for product.product_category.
type CategoryRecord struct { type CategoryRecord struct {
ID string ID string
@ -489,10 +483,10 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (*
} }
// ListCategoryProducts loads paginated product summaries for a category ID. // ListCategoryProducts loads paginated product summaries for a category ID.
func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, map[string][]CategoryProductSKURecord, int64, error) { func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) {
parsedCategoryID, err := parseID(categoryID, "category id") parsedCategoryID, err := parseID(categoryID, "category id")
if err != nil { if err != nil {
return nil, nil, 0, err return nil, 0, err
} }
if page < 1 { if page < 1 {
@ -510,10 +504,10 @@ JOIN product.product_category_bindings b ON b.product_id = p.id
WHERE b.category_id = $1 WHERE b.category_id = $1
AND p.deleted_at IS NULL AND p.deleted_at IS NULL
`, parsedCategoryID).Scan(&total); err != nil { `, parsedCategoryID).Scan(&total); err != nil {
return nil, nil, 0, fmt.Errorf("count category products: %w", err) return nil, 0, fmt.Errorf("count category products: %w", err)
} }
if total == 0 { if total == 0 {
return []*CategoryProductRecord{}, map[string][]CategoryProductSKURecord{}, 0, nil return []*CategoryProductRecord{}, 0, nil
} }
offset := int64(page-1) * int64(pageSize) offset := int64(page-1) * int64(pageSize)
@ -524,16 +518,26 @@ SELECT p.updated_at,
p.id, p.id,
p.spu_no, p.spu_no,
p.status, p.status,
COALESCE(to_json(p.image_ids)::text, '[]') COALESCE(to_json(p.image_ids)::text, '[]'),
COALESCE(sku_summary.price, 0),
COALESCE(sku_summary.sold_quantity, 0)
FROM product.products p FROM product.products p
JOIN product.product_category_bindings b ON b.product_id = p.id JOIN product.product_category_bindings b ON b.product_id = p.id
LEFT JOIN LATERAL (
SELECT MIN(pi.price) AS price,
SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity
FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
WHERE pi.product_id = p.id
AND pi.deleted_at IS NULL
) sku_summary ON TRUE
WHERE b.category_id = $1 WHERE b.category_id = $1
AND p.deleted_at IS NULL AND p.deleted_at IS NULL
ORDER BY p.created_at DESC, p.id DESC ORDER BY p.created_at DESC, p.id DESC
LIMIT $2 OFFSET $3 LIMIT $2 OFFSET $3
`, parsedCategoryID, pageSize, offset) `, parsedCategoryID, pageSize, offset)
if err != nil { if err != nil {
return nil, nil, 0, fmt.Errorf("query category products: %w", err) return nil, 0, fmt.Errorf("query category products: %w", err)
} }
defer rows.Close() defer rows.Close()
@ -541,28 +545,14 @@ LIMIT $2 OFFSET $3
for rows.Next() { for rows.Next() {
product, err := scanCategoryProduct(rows) product, err := scanCategoryProduct(rows)
if err != nil { if err != nil {
return nil, nil, 0, err return nil, 0, err
} }
products = append(products, product) products = append(products, product)
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
return nil, nil, 0, fmt.Errorf("iterate category products: %w", err) return nil, 0, fmt.Errorf("iterate category products: %w", err)
} }
if len(products) == 0 { return products, total, nil
return products, map[string][]CategoryProductSKURecord{}, total, nil
}
foundIDs := make([]string, 0, len(products))
for _, product := range products {
foundIDs = append(foundIDs, product.ID)
}
skuMap, err := r.loadCategoryProductSKUsByProductIDs(ctx, foundIDs)
if err != nil {
return nil, nil, 0, err
}
return products, skuMap, total, nil
} }
// ListCategoryTreeNodes loads product category nodes for storefront category trees. // ListCategoryTreeNodes loads product category nodes for storefront category trees.
@ -1034,55 +1024,6 @@ ORDER BY pi.created_at ASC
return result, nil return result, nil
} }
func (r *ProductRepository) loadCategoryProductSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]CategoryProductSKURecord, error) {
result := make(map[string][]CategoryProductSKURecord, len(productIDs))
if len(productIDs) == 0 {
return result, nil
}
placeholders := make([]string, len(productIDs))
args := make([]any, len(productIDs))
for i, id := range productIDs {
parsed, err := parseID(id, "product id")
if err != nil {
return nil, err
}
placeholders[i] = fmt.Sprintf("$%d", i+1)
args[i] = parsed
}
query := fmt.Sprintf(`
SELECT pi.id,
pi.product_id,
COALESCE(inv.available_quantity, 0),
pi.price
FROM product.product_items pi
LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id
WHERE pi.product_id IN (%s)
AND pi.deleted_at IS NULL
ORDER BY pi.created_at ASC
`, strings.Join(placeholders, ", "))
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("query category product skus: %w", err)
}
defer rows.Close()
for rows.Next() {
sku, err := scanCategoryProductSKU(rows)
if err != nil {
return nil, err
}
result[sku.ProductID] = append(result[sku.ProductID], *sku)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate category product skus: %w", err)
}
return result, nil
}
type rowScanner interface { type rowScanner interface {
Scan(dest ...any) error Scan(dest ...any) error
} }
@ -1102,6 +1043,8 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
&rec.SPUNo, &rec.SPUNo,
&status, &status,
&imageIDsJSON, &imageIDsJSON,
&rec.Price,
&rec.SoldQuantity,
); err != nil { ); err != nil {
return nil, fmt.Errorf("scan category product: %w", err) return nil, fmt.Errorf("scan category product: %w", err)
} }
@ -1116,26 +1059,6 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) {
return &rec, nil return &rec, nil
} }
func scanCategoryProductSKU(scanner rowScanner) (*CategoryProductSKURecord, error) {
var (
rec CategoryProductSKURecord
id int64
productID int64
)
if err := scanner.Scan(
&id,
&productID,
&rec.AvailableQuantity,
&rec.Price,
); err != nil {
return nil, fmt.Errorf("scan category product sku: %w", err)
}
rec.ID = formatID(id)
rec.ProductID = formatID(productID)
return &rec, nil
}
func scanProduct(scanner rowScanner) (*ProductRecord, error) { func scanProduct(scanner rowScanner) (*ProductRecord, error) {
var ( var (
rec ProductRecord rec ProductRecord

View File

@ -177,7 +177,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
)) ))
defer dbSpan.End() defer dbSpan.End()
products, skuMap, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize) products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize)
if err != nil { if err != nil {
dbSpan.RecordError(err) dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error()) dbSpan.SetStatus(otelcodes.Error, err.Error())
@ -189,7 +189,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1
protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) protoProducts := make([]*productv1.CategoryProduct, 0, len(products))
for _, product := range products { for _, product := range products {
protoProducts = append(protoProducts, toProtoCategoryProduct(product, skuMap[product.ID])) protoProducts = append(protoProducts, toProtoCategoryProduct(product))
} }
return &productv1.ListCategoryProductsResponse{ return &productv1.ListCategoryProductsResponse{
@ -761,18 +761,10 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
} }
} }
func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []repository.CategoryProductSKURecord) *productv1.CategoryProduct { func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv1.CategoryProduct {
if product == nil { if product == nil {
return nil return nil
} }
protoSKUs := make([]*productv1.CategoryProductSKU, 0, len(skus))
for _, sku := range skus {
protoSKUs = append(protoSKUs, &productv1.CategoryProductSKU{
SkuId: sku.ID,
AvailableQuantity: sku.AvailableQuantity,
Price: sku.Price,
})
}
return &productv1.CategoryProduct{ return &productv1.CategoryProduct{
UpdatedAt: timeToMillisString(product.UpdatedAt), UpdatedAt: timeToMillisString(product.UpdatedAt),
CreatedAt: timeToMillisString(product.CreatedAt), CreatedAt: timeToMillisString(product.CreatedAt),
@ -781,7 +773,8 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []re
SpuNo: product.SPUNo, SpuNo: product.SPUNo,
Status: product.Status, Status: product.Status,
ImageIds: product.ImageIDs, ImageIds: product.ImageIDs,
Skus: protoSKUs, Price: product.Price,
SoldQuantity: product.SoldQuantity,
} }
} }