From a6bca494f46ed03531df1e5ceaa5445ffeb4f11f Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Tue, 14 Jul 2026 18:57:26 +0800 Subject: [PATCH] =?UTF-8?q?feat(product):=20=E8=81=9A=E5=90=88=E5=88=86?= =?UTF-8?q?=E7=B1=BB=E5=95=86=E5=93=81=E6=9C=80=E4=BD=8E=E4=BB=B7=E4=B8=8E?= =?UTF-8?q?=E9=94=80=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + internal/repository/product_repository.go | 137 +++++----------------- internal/server/product_server.go | 31 ++--- 3 files changed, 44 insertions(+), 126 deletions(-) diff --git a/README.md b/README.md index 3a05c0b..946c47e 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `total` | `int64` | 分类/分组下商品总数 | | `total_pages` | `int32` | 总页数 | +`products[]` 返回商品摘要以及全部未删除 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。 + `products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。 ### `ListCategoryTree` diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 3fcfd67..bef4b2a 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -90,21 +90,15 @@ type InventoryRecord struct { // CategoryProductRecord is the product summary returned by category product lists. type CategoryProductRecord struct { - ID string - SPUNo string - Title string - Status productv1.ProductStatus - ImageIDs []string - CreatedAt 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 + ID string + SPUNo string + Title string + Status productv1.ProductStatus + ImageIDs []string + Price int64 + SoldQuantity int64 + CreatedAt time.Time + UpdatedAt time.Time } // CategoryRecord is the persistence model for product.product_category. @@ -489,10 +483,10 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* } // 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") if err != nil { - return nil, nil, 0, err + return nil, 0, err } if page < 1 { @@ -510,10 +504,10 @@ JOIN product.product_category_bindings b ON b.product_id = p.id WHERE b.category_id = $1 AND p.deleted_at IS NULL `, 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 { - return []*CategoryProductRecord{}, map[string][]CategoryProductSKURecord{}, 0, nil + return []*CategoryProductRecord{}, 0, nil } offset := int64(page-1) * int64(pageSize) @@ -524,16 +518,26 @@ SELECT p.updated_at, p.id, p.spu_no, 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 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 AND p.deleted_at IS NULL ORDER BY p.created_at DESC, p.id DESC LIMIT $2 OFFSET $3 `, parsedCategoryID, pageSize, offset) 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() @@ -541,28 +545,14 @@ LIMIT $2 OFFSET $3 for rows.Next() { product, err := scanCategoryProduct(rows) if err != nil { - return nil, nil, 0, err + return nil, 0, err } products = append(products, product) } 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, 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 + return products, total, nil } // ListCategoryTreeNodes loads product category nodes for storefront category trees. @@ -1034,55 +1024,6 @@ ORDER BY pi.created_at ASC 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 { Scan(dest ...any) error } @@ -1102,6 +1043,8 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { &rec.SPUNo, &status, &imageIDsJSON, + &rec.Price, + &rec.SoldQuantity, ); err != nil { return nil, fmt.Errorf("scan category product: %w", err) } @@ -1116,26 +1059,6 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { 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) { var ( rec ProductRecord diff --git a/internal/server/product_server.go b/internal/server/product_server.go index b0756bd..f218816 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -177,7 +177,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 )) 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 { dbSpan.RecordError(err) 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)) for _, product := range products { - protoProducts = append(protoProducts, toProtoCategoryProduct(product, skuMap[product.ID])) + protoProducts = append(protoProducts, toProtoCategoryProduct(product)) } return &productv1.ListCategoryProductsResponse{ @@ -761,27 +761,20 @@ 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 { 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{ - UpdatedAt: timeToMillisString(product.UpdatedAt), - CreatedAt: timeToMillisString(product.CreatedAt), - Title: product.Title, - ProductId: product.ID, - SpuNo: product.SPUNo, - Status: product.Status, - ImageIds: product.ImageIDs, - Skus: protoSKUs, + UpdatedAt: timeToMillisString(product.UpdatedAt), + CreatedAt: timeToMillisString(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Price: product.Price, + SoldQuantity: product.SoldQuantity, } }