From 2ef7742b6a48ef92a886d737d7e09e872cfdaf86 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 11:58:27 +0800 Subject: [PATCH] Implement CreateProduct and ListCategoryProducts functionalities in the product server, enhancing product management capabilities. Update README with new RPC methods and examples. Refactor product repository to support SKU insertion and category-based product listing, ensuring efficient data handling and retrieval. --- README.md | 10 ++ internal/repository/product_repository.go | 151 ++++++++++++++++++ internal/server/product_server.go | 178 ++++++++++++++++++++++ 3 files changed, 339 insertions(+) diff --git a/README.md b/README.md index 653a82b..fbc43da 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,9 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格 | RPC | 说明 | 主要调用方 | |-----|------|-----------| +| `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 / 订单服务 | +| `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | | `BatchGetProducts` | 批量拉取商品快照,减少算价阶段 N 次 RPC | `ids-svc-order` | 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 @@ -88,9 +90,17 @@ grpcurl -plaintext localhost:50052 list grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct +# 创建商品 +grpcurl -plaintext -d '{"product":{"product_id":"","spu_code":"","name":"商品名称","description":"商品描述","status":"PRODUCT_STATUS_DRAFT","skus":[]}}' \ + localhost:50052 ids.product.v1.ProductService/CreateProduct + # 批量查询 grpcurl -plaintext -d '{"product_ids":["",""]}' \ localhost:50052 ids.product.v1.ProductService/BatchGetProducts + +# 分页查询分类商品 +grpcurl -plaintext -d '{"category_id":"","page":1,"page_size":20}' \ + localhost:50052 ids.product.v1.ProductService/ListCategoryProducts ``` ## 数据模型 diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index beae8c4..e64acb1 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -99,6 +99,48 @@ VALUES ($1, $2, $3, $4, $5, $6::jsonb) return nil } +// CreateProductWithSKUs inserts an SPU and its optional SKU list in one transaction. +func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product ProductRecord, skus []SKURecord) (*ProductRecord, []SKURecord, error) { + attrs, err := json.Marshal(product.Attrs) + if err != nil { + return nil, nil, fmt.Errorf("marshal product attrs: %w", err) + } + if product.Attrs == nil { + attrs = []byte("{}") + } + + id, err := parseID(product.ID, "product id") + if err != nil { + return nil, nil, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, nil, fmt.Errorf("begin create product: %w", err) + } + defer tx.Rollback() + + createdProduct, err := insertProduct(ctx, tx, id, product, attrs) + if err != nil { + return nil, nil, err + } + + createdSKUs := make([]SKURecord, 0, len(skus)) + for _, sku := range skus { + createdSKU, err := insertSKU(ctx, tx, product.ID, sku) + if err != nil { + return nil, nil, err + } + createdSKUs = append(createdSKUs, *createdSKU) + } + + if err := tx.Commit(); err != nil { + return nil, nil, fmt.Errorf("commit create product: %w", err) + } + + return createdProduct, createdSKUs, nil +} + // UpdateProduct updates mutable SPU fields. func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error { attrs, err := json.Marshal(product.Attrs) @@ -274,6 +316,73 @@ func (r *ProductRepository) BatchGetProducts(ctx context.Context, productIDs []s return products, skuMap, nil } +// ListCategoryProducts loads a paginated product list for a category ID. +func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*ProductRecord, map[string][]SKURecord, int64, error) { + parsedCategoryID, err := parseID(categoryID, "category id") + if err != nil { + return nil, nil, 0, err + } + + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + + var total int64 + if err := r.db.QueryRowContext(ctx, ` +SELECT COUNT(*) +FROM product.products +WHERE category_ids @> ARRAY[$1]::BIGINT[] +`, parsedCategoryID).Scan(&total); err != nil { + return nil, nil, 0, fmt.Errorf("count category products: %w", err) + } + if total == 0 { + return []*ProductRecord{}, map[string][]SKURecord{}, 0, nil + } + + offset := int64(page-1) * int64(pageSize) + rows, err := r.db.QueryContext(ctx, ` +SELECT id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +FROM product.products +WHERE category_ids @> ARRAY[$1]::BIGINT[] +ORDER BY created_at DESC, id DESC +LIMIT $2 OFFSET $3 +`, parsedCategoryID, pageSize, offset) + if err != nil { + return nil, nil, 0, fmt.Errorf("query category products: %w", err) + } + defer rows.Close() + + products := make([]*ProductRecord, 0, pageSize) + for rows.Next() { + product, err := scanProduct(rows) + if err != nil { + return nil, nil, 0, err + } + products = append(products, product) + } + if err := rows.Err(); err != nil { + return nil, nil, 0, fmt.Errorf("iterate category products: %w", err) + } + if len(products) == 0 { + return products, map[string][]SKURecord{}, total, nil + } + + foundIDs := make([]string, 0, len(products)) + for _, product := range products { + foundIDs = append(foundIDs, product.ID) + } + + skuMap, err := r.loadSKUsByProductIDs(ctx, foundIDs) + if err != nil { + return nil, nil, 0, err + } + + return products, skuMap, total, nil +} + func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) { products, err := r.loadProductsByIDs(ctx, []string{productID}) if err != nil { @@ -325,6 +434,48 @@ ORDER BY created_at ASC return products, nil } +func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRecord, attrs []byte) (*ProductRecord, error) { + row := tx.QueryRowContext(ctx, ` +INSERT INTO product.products (id, spu_no, title, sell_point, status, cross_border) +VALUES ($1, $2, $3, $4, $5, $6::jsonb) +RETURNING id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) + + createdProduct, err := scanProduct(row) + if err != nil { + return nil, fmt.Errorf("insert product %s: %w", product.ID, err) + } + return createdProduct, nil +} + +func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) { + attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) + if err != nil { + return nil, err + } + + id, err := parseID(sku.ID, "sku id") + if err != nil { + return nil, err + } + parsedProductID, err := parseID(productID, "product id") + if err != nil { + return nil, err + } + + row := tx.QueryRowContext(ctx, ` +INSERT INTO product.skus (id, product_id, name, price, stock, attributes) +VALUES ($1, $2, $3, $4, $5, $6::jsonb) +RETURNING id, product_id, name, price, stock, attributes, created_at, updated_at +`, id, parsedProductID, sku.Name, sku.Price, sku.Stock, attrs) + + createdSKU, err := scanSKU(row) + if err != nil { + return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) + } + return createdSKU, nil +} + func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) { result := make(map[string][]SKURecord, len(productIDs)) if len(productIDs) == 0 { diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 603dff2..3b22756 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -2,7 +2,11 @@ package server import ( "context" + "encoding/json" "errors" + "math" + "strconv" + "strings" "go.uber.org/zap" "google.golang.org/grpc/codes" @@ -14,6 +18,11 @@ import ( "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" ) +const ( + defaultPageSize = int32(20) + maxPageSize = int32(100) +) + // ProductServer implements productv1.ProductServiceServer. type ProductServer struct { productv1.UnimplementedProductServiceServer @@ -33,6 +42,28 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger) *P } } +// CreateProduct creates a product SPU and optional SKU list. +func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) { + if req == nil || req.GetProduct() == nil { + return nil, status.Error(codes.InvalidArgument, "product is required") + } + + product, skus, err := productFromProto(req.GetProduct()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + createdProduct, createdSKUs, err := s.repo.CreateProductWithSKUs(ctx, product, skus) + if err != nil { + s.logger.Error("create product failed", zap.String("product_id", product.ID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "create product: %v", err) + } + + return &productv1.CreateProductResponse{ + Product: toProtoProduct(createdProduct, createdSKUs), + }, nil +} + // GetProduct returns a single SPU and its SKU list. func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProductRequest) (*productv1.GetProductResponse, error) { if req == nil || req.GetProductId() == "" { @@ -75,6 +106,152 @@ func (s *ProductServer) BatchGetProducts(ctx context.Context, req *productv1.Bat }, nil } +// ListCategoryProducts returns a paginated product list under a category. +func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { + if req == nil || req.GetCategoryId() == "" { + return nil, status.Error(codes.InvalidArgument, "category_id is required") + } + categoryID, err := strconv.ParseInt(req.GetCategoryId(), 10, 64) + if err != nil || categoryID <= 0 { + return nil, status.Error(codes.InvalidArgument, "category_id must be a positive snowflake id") + } + + page := req.GetPage() + if page <= 0 { + page = 1 + } + pageSize := req.GetPageSize() + if pageSize <= 0 { + pageSize = defaultPageSize + } + if pageSize > maxPageSize { + pageSize = maxPageSize + } + + products, skuMap, total, err := s.repo.ListCategoryProducts(ctx, req.GetCategoryId(), page, pageSize) + if err != nil { + s.logger.Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "list category products: %v", err) + } + + protoProducts := make([]*productv1.Product, 0, len(products)) + for _, product := range products { + protoProducts = append(protoProducts, toProtoProduct(product, skuMap[product.ID])) + } + + return &productv1.ListCategoryProductsResponse{ + Products: protoProducts, + Page: page, + PageSize: pageSize, + Total: total, + TotalPages: totalPages(total, pageSize), + }, nil +} + +func totalPages(total int64, pageSize int32) int32 { + if total <= 0 || pageSize <= 0 { + return 0 + } + pages := (total + int64(pageSize) - 1) / int64(pageSize) + if pages > math.MaxInt32 { + return math.MaxInt32 + } + return int32(pages) +} + +func productFromProto(product *productv1.Product) (repository.ProductRecord, []repository.SKURecord, error) { + productID := strings.TrimSpace(product.GetProductId()) + if err := validatePositiveID(productID, "product_id"); err != nil { + return repository.ProductRecord{}, nil, err + } + + spuCode := strings.TrimSpace(product.GetSpuCode()) + if spuCode == "" { + return repository.ProductRecord{}, nil, errors.New("spu_code is required") + } + + name := strings.TrimSpace(product.GetName()) + if name == "" { + return repository.ProductRecord{}, nil, errors.New("name is required") + } + + statusValue := product.GetStatus() + if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { + statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT + } + + record := repository.ProductRecord{ + ID: productID, + SPUCode: spuCode, + Name: name, + Description: product.GetDescription(), + Status: statusValue, + Attrs: map[string]any{}, + } + + skus := make([]repository.SKURecord, 0, len(product.GetSkus())) + for i, protoSKU := range product.GetSkus() { + sku, err := skuFromProto(productID, protoSKU) + if err != nil { + return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) + } + skus = append(skus, sku) + } + + return record, skus, nil +} + +func skuFromProto(productID string, sku *productv1.SKU) (repository.SKURecord, error) { + if sku == nil { + return repository.SKURecord{}, errors.New("sku is required") + } + + skuID := strings.TrimSpace(sku.GetSkuId()) + if err := validatePositiveID(skuID, "sku_id"); err != nil { + return repository.SKURecord{}, err + } + + if sku.GetProductId() != "" && sku.GetProductId() != productID { + return repository.SKURecord{}, errors.New("product_id must match product.product_id") + } + + name := strings.TrimSpace(sku.GetName()) + if name == "" { + return repository.SKURecord{}, errors.New("name is required") + } + if sku.GetPrice() < 0 { + return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") + } + if sku.GetStock() < 0 { + return repository.SKURecord{}, errors.New("stock must be greater than or equal to 0") + } + + attrs := strings.TrimSpace(sku.GetAttributesJsonb()) + if attrs != "" && !json.Valid([]byte(attrs)) { + return repository.SKURecord{}, errors.New("attributes_jsonb must be valid json") + } + + return repository.SKURecord{ + ID: skuID, + ProductID: productID, + Name: name, + Price: sku.GetPrice(), + Stock: sku.GetStock(), + AttributesJSONB: attrs, + }, nil +} + +func validatePositiveID(raw, field string) error { + if raw == "" { + return errors.New(field + " is required") + } + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return errors.New(field + " must be a positive snowflake id") + } + return nil +} + func toProtoProduct(product *repository.ProductRecord, skus []repository.SKURecord) *productv1.Product { if product == nil { return nil @@ -94,6 +271,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco return &productv1.Product{ ProductId: product.ID, + SpuCode: product.SPUCode, Name: product.Name, Description: product.Description, Status: product.Status,