From 548ed1995466f83b945830bd3640a4202c165902 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Wed, 8 Jul 2026 14:41:16 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E7=B1=BB=E5=88=AB=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 25 ++++++- docs/ARCHITECTURE.md | 2 + internal/observability/observability.go | 14 ++++ internal/repository/product_repository.go | 76 +++++++++++++++++++++- internal/server/product_server.go | 79 +++++++++++++++++++++++ 5 files changed, 194 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6c20ba5..985b402 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | +| `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF | 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 @@ -23,6 +24,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 | | `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 | | `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 | +| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 | ### `CreateProduct` @@ -71,6 +73,27 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `total` | `int64` | 分类/分组下商品总数 | | `total_pages` | `int32` | 总页数 | +### `ListCategoryTree` + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `only_visible` | `bool` | 否 | 为 `true` 时只返回 `status = 1` 的分类;为 `false` 时返回全部 `node_type = 0` 分类 | + +响应 `categories` 为树形分类列表。一级分类位于最外层,子分类挂载在父分类的 `children` 下。 + +`CategoryNode` 字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `category_id` | `string` | 分类节点 ID,对应 `product.product_category.id` | +| `name` | `string` | 分类展示名称 | +| `parent_id` | `string` | 父级分类 ID;一级分类为空字符串 | +| `level` | `int32` | 分类层级 | +| `image_json` | `string` | 分类图片 JSON,原样返回 | +| `sort_num` | `int32` | 同级排序值 | +| `status` | `int32` | 节点状态:`0` 隐藏,`1` 显示 | +| `children` | `CategoryNode[]` | 子分类列表 | + ## 技术栈 | 项 | 选型 | @@ -138,7 +161,7 @@ cp .env.example .env | gRPC 健康检查 | `grpc.health.v1.Health/Check` | 注册标准 gRPC Health Checking | | Prometheus 指标 | `GET /metrics` | 暴露 Go runtime、process、RPC 与商品业务指标 | | RPC 指标 | `ids_product_grpc_requests_total`, `ids_product_grpc_request_duration_seconds` | 按 `method`、`code` 维度统计请求数和耗时 | -| 商品业务指标 | `ids_product_products_created_total`, `ids_product_category_product_lists_total` | 统计商品创建成功数和分类商品查询成功数 | +| 商品业务指标 | `ids_product_products_created_total`, `ids_product_category_product_lists_total`, `ids_product_category_tree_lists_total` | 统计商品创建成功数、分类商品查询成功数和分类树查询成功数 | | 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、分类商品查询补充业务 span | | 结构化日志 | stdout | access log 与错误日志包含 `trace_id`、`span_id`、`correlation_id` | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fd19f74..4ac31a5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -75,12 +75,14 @@ | `CreateProduct` | 后台 / 运营系统 | 创建商品 SPU 及可选 SKU 列表。 | | `GetProduct` | BFF / 后台 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 | | `ListCategoryProducts` | BFF / 商城前台 | 根据分类/分组节点分页返回商品列表。 | +| `ListCategoryTree` | 微信小程序分类页 / BFF | 返回 `node_type = 0` 的商品分类树,子分类挂载在父分类 `children` 下。 | ### 3.2 查询实现约束 1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。 2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 +4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。 --- diff --git a/internal/observability/observability.go b/internal/observability/observability.go index 658055f..52d6ba9 100644 --- a/internal/observability/observability.go +++ b/internal/observability/observability.go @@ -64,6 +64,15 @@ var ( Help: "Total number of successful category product list queries.", }, ) + + categoryTreeListsTotal = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "category_tree_lists_total", + Help: "Total number of successful category tree queries.", + }, + ) ) // Observer wires OTLP tracing and trace-aware structured logging. @@ -200,6 +209,11 @@ func IncCategoryProductLists() { categoryProductListsTotal.Inc() } +// IncCategoryTreeLists records a successful category tree query. +func IncCategoryTreeLists() { + categoryTreeListsTotal.Inc() +} + // MetricsServer exposes Prometheus scrape and health endpoints. func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server { mux := http.NewServeMux() diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index b7e2bde..f5ba283 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -43,6 +43,17 @@ type SKURecord struct { UpdatedAt time.Time } +// CategoryRecord is the persistence model for product.product_category. +type CategoryRecord struct { + ID string + Name string + ParentID string + Level int32 + ImageJSON string + SortNum int32 + Status int32 +} + // ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. type ProductRepository struct { db *sql.DB @@ -419,6 +430,41 @@ LIMIT $2 OFFSET $3 return products, skuMap, total, nil } +// ListCategoryTreeNodes loads product category nodes for storefront category trees. +func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { + rows, err := r.db.QueryContext(ctx, ` +SELECT id, + name, + parent_id, + level, + image_json, + sort_num, + status +FROM product.product_category +WHERE node_type = 0 + AND ($1 = false OR status = 1) +ORDER BY level ASC, sort_num ASC, id ASC +`, onlyVisible) + if err != nil { + return nil, fmt.Errorf("query category tree nodes: %w", err) + } + defer rows.Close() + + categories := make([]*CategoryRecord, 0) + for rows.Next() { + category, err := scanCategory(rows) + if err != nil { + return nil, err + } + categories = append(categories, category) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate category tree nodes: %w", err) + } + + return categories, nil +} + func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) { products, err := r.loadProductsByIDs(ctx, []string{productID}) if err != nil { @@ -554,7 +600,7 @@ SELECT pi.id, pi.product_id, pi.name, pi.price, - COALESCE(inv.available_quantity, 0), + COALESCE(inv.sold_quantity, 0), pi.attributes, pi.created_at, pi.updated_at @@ -634,6 +680,34 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { return &rec, nil } +func scanCategory(scanner rowScanner) (*CategoryRecord, error) { + var ( + rec CategoryRecord + id int64 + parentID sql.NullInt64 + imageJSON []byte + level int16 + status int16 + ) + if err := scanner.Scan( + &id, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, + ); err != nil { + return nil, fmt.Errorf("scan category: %w", err) + } + + rec.ID = formatID(id) + if parentID.Valid { + rec.ParentID = formatID(parentID.Int64) + } + rec.Level = int32(level) + rec.ImageJSON = string(imageJSON) + if rec.ImageJSON == "" { + rec.ImageJSON = "[]" + } + rec.Status = int32(status) + return &rec, nil +} + func normalizeAttributesJSON(raw string) ([]byte, error) { if strings.TrimSpace(raw) == "" { return []byte("{}"), nil diff --git a/internal/server/product_server.go b/internal/server/product_server.go index d585a3a..314da9b 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -161,6 +161,33 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 }, nil } +// ListCategoryTree returns product category nodes as a parent-child hierarchy. +func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) { + onlyVisible := false + if req != nil { + onlyVisible = req.GetOnlyVisible() + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_category_tree", trace.WithAttributes( + attribute.Bool("category.only_visible", onlyVisible), + )) + defer dbSpan.End() + + categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("list category tree failed", zap.Bool("only_visible", onlyVisible), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "list category tree: %v", err) + } + dbSpan.SetAttributes(attribute.Int("category.result_count", len(categories))) + observability.IncCategoryTreeLists() + + return &productv1.ListCategoryTreeResponse{ + Categories: buildCategoryTree(categories), + }, nil +} + func totalPages(total int64, pageSize int32) int32 { if total <= 0 || pageSize <= 0 { return 0 @@ -289,3 +316,55 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco UpdatedAt: timestamppb.New(product.UpdatedAt), } } + +func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode { + nodes := make(map[string]*productv1.CategoryNode, len(categories)) + records := make(map[string]*repository.CategoryRecord, len(categories)) + orderedIDs := make([]string, 0, len(categories)) + + for _, category := range categories { + if category == nil || category.ID == "" { + continue + } + nodes[category.ID] = toProtoCategoryNode(category) + records[category.ID] = category + orderedIDs = append(orderedIDs, category.ID) + } + + roots := make([]*productv1.CategoryNode, 0) + for _, id := range orderedIDs { + node := nodes[id] + record := records[id] + if node == nil || record == nil { + continue + } + + parentID := record.ParentID + parent, parentExists := nodes[parentID] + parentRecord := records[parentID] + if parentID == "" || !parentExists || parentRecord == nil || parentID == id || parentRecord.Level >= record.Level { + roots = append(roots, node) + continue + } + + parent.Children = append(parent.Children, node) + } + + return roots +} + +func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.CategoryNode { + if category == nil { + return nil + } + return &productv1.CategoryNode{ + CategoryId: category.ID, + Name: category.Name, + ParentId: category.ParentID, + Level: category.Level, + ImageJson: category.ImageJSON, + SortNum: category.SortNum, + Status: category.Status, + Children: []*productv1.CategoryNode{}, + } +} From 5e74ff281643e1fac529412ef2655afb34de4cb4 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Thu, 9 Jul 2026 15:41:19 +0800 Subject: [PATCH 2/7] =?UTF-8?q?=E8=B0=83=E6=95=B4=20=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/repository/product_repository.go | 470 ++++++++++++++++++++-- internal/server/product_server.go | 89 +++- 2 files changed, 508 insertions(+), 51 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index f5ba283..ce96653 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -21,31 +21,82 @@ var ErrSKUNotFound = errors.New("sku not found") // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { - ID string - SPUNo string - Title string - SellingPoint string - Status productv1.ProductStatus - Attrs map[string]any - CreatedAt time.Time - UpdatedAt time.Time + ID string + SPUNo string + Title string + SellingPoint string + BrandID string + SupplierID string + ImageIDs []string + DetailHTML string + MemberDiscountEnabled bool + GoodsType int32 + ServiceGuarantees []string + Status productv1.ProductStatus + Attrs map[string]any + CrossBorderJSON string + FreightChargeType int32 + FreightFixedAmount int64 + FreightTemplateID string + SaleTimeType int32 + ScheduledSaleTime *time.Time + DeletedAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time } // SKURecord is the persistence model for product.product_items. type SKURecord struct { ID string ProductID string + SKUNo string Name string Price int64 AvailableQuantity int32 + LockedQuantity int32 + SoldQuantity int32 AttributesJSON string + Status int32 + DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time + Inventory *InventoryRecord +} + +// InventoryRecord is the persistence model for product.product_item_inventory. +type InventoryRecord struct { + ID string + SKUID string + AvailableQuantity int32 + LockedQuantity int32 + SoldQuantity int32 + CreatedAt time.Time + UpdatedAt time.Time +} + +// 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 } // CategoryRecord is the persistence model for product.product_category. type CategoryRecord struct { ID string + NodeType int32 Name string ParentID string Level int32 @@ -265,7 +316,7 @@ VALUES ($1, $2, $3, $4, $5::jsonb) return fmt.Errorf("insert sku %s: %w", sku.ID, err) } - if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { return err } @@ -309,7 +360,7 @@ WHERE id = $1 return ErrSKUNotFound } - if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { return err } @@ -359,8 +410,8 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* return product, skus[productID], 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) { +// 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) { parsedCategoryID, err := parseID(categoryID, "category id") if err != nil { return nil, nil, 0, err @@ -384,12 +435,18 @@ WHERE b.category_id = $1 return nil, nil, 0, fmt.Errorf("count category products: %w", err) } if total == 0 { - return []*ProductRecord{}, map[string][]SKURecord{}, 0, nil + return []*CategoryProductRecord{}, map[string][]CategoryProductSKURecord{}, 0, nil } offset := int64(page-1) * int64(pageSize) rows, err := r.db.QueryContext(ctx, ` -SELECT p.id, p.spu_no, p.title, COALESCE(p.selling_point, ''), p.status, p.cross_border, p.created_at, p.updated_at +SELECT p.updated_at, + p.created_at, + p.title, + p.id, + p.spu_no, + p.status, + COALESCE(to_json(p.image_ids)::text, '[]') FROM product.products p JOIN product.product_category_bindings b ON b.product_id = p.id WHERE b.category_id = $1 @@ -402,9 +459,9 @@ LIMIT $2 OFFSET $3 } defer rows.Close() - products := make([]*ProductRecord, 0, pageSize) + products := make([]*CategoryProductRecord, 0, pageSize) for rows.Next() { - product, err := scanProduct(rows) + product, err := scanCategoryProduct(rows) if err != nil { return nil, nil, 0, err } @@ -414,7 +471,7 @@ LIMIT $2 OFFSET $3 return nil, nil, 0, fmt.Errorf("iterate category products: %w", err) } if len(products) == 0 { - return products, map[string][]SKURecord{}, total, nil + return products, map[string][]CategoryProductSKURecord{}, total, nil } foundIDs := make([]string, 0, len(products)) @@ -422,7 +479,7 @@ LIMIT $2 OFFSET $3 foundIDs = append(foundIDs, product.ID) } - skuMap, err := r.loadSKUsByProductIDs(ctx, foundIDs) + skuMap, err := r.loadCategoryProductSKUsByProductIDs(ctx, foundIDs) if err != nil { return nil, nil, 0, err } @@ -434,6 +491,7 @@ LIMIT $2 OFFSET $3 func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { rows, err := r.db.QueryContext(ctx, ` SELECT id, + node_type, name, parent_id, level, @@ -489,7 +547,27 @@ func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs [] } query := fmt.Sprintf(` -SELECT id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at +SELECT id, + spu_no, + title, + COALESCE(selling_point, ''), + brand_id, + supplier_id, + COALESCE(to_json(image_ids)::text, '[]'), + COALESCE(detail_html, ''), + member_discount_enabled, + goods_type, + COALESCE(to_json(service_guarantees)::text, '[]'), + status, + cross_border, + freight_charge_type, + freight_fixed_amount, + freight_template_id, + sale_time_type, + scheduled_sale_time, + deleted_at, + created_at, + updated_at FROM product.products WHERE id IN (%s) AND deleted_at IS NULL @@ -521,7 +599,27 @@ func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRec row := tx.QueryRowContext(ctx, ` INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) VALUES ($1, $2, $3, $4, $5, $6::jsonb) -RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at +RETURNING id, + spu_no, + title, + COALESCE(selling_point, ''), + brand_id, + supplier_id, + COALESCE(to_json(image_ids)::text, '[]'), + COALESCE(detail_html, ''), + member_discount_enabled, + goods_type, + COALESCE(to_json(service_guarantees)::text, '[]'), + status, + cross_border, + freight_charge_type, + freight_fixed_amount, + freight_template_id, + sale_time_type, + scheduled_sale_time, + deleted_at, + created_at, + updated_at `, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) createdProduct, err := scanProduct(row) @@ -549,7 +647,23 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) row := tx.QueryRowContext(ctx, ` INSERT INTO product.product_items (id, product_id, name, price, attributes) VALUES ($1, $2, $3, $4, $5::jsonb) -RETURNING id, product_id, name, price, 0, attributes, created_at, updated_at +RETURNING id, + product_id, + sku_no, + name, + price, + attributes, + status, + deleted_at, + created_at, + updated_at, + NULL::bigint, + NULL::bigint, + NULL::integer, + NULL::integer, + NULL::integer, + NULL::timestamptz, + NULL::timestamptz `, id, parsedProductID, sku.Name, sku.Price, attrs) createdSKU, err := scanSKU(row) @@ -557,25 +671,33 @@ RETURNING id, product_id, name, price, 0, attributes, created_at, updated_at return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) } - if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + inventory, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity) + if err != nil { return nil, err } - createdSKU.AvailableQuantity = sku.AvailableQuantity + createdSKU.Inventory = inventory + if inventory != nil { + createdSKU.AvailableQuantity = inventory.AvailableQuantity + createdSKU.LockedQuantity = inventory.LockedQuantity + createdSKU.SoldQuantity = inventory.SoldQuantity + } return createdSKU, nil } -func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) error { - _, err := tx.ExecContext(ctx, ` +func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) (*InventoryRecord, error) { + row := tx.QueryRowContext(ctx, ` INSERT INTO product.product_item_inventory (id, sku_id, available_quantity) VALUES ($1, $1, $2) ON CONFLICT (sku_id) DO UPDATE SET available_quantity = EXCLUDED.available_quantity, updated_at = NOW() +RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at `, skuID, availableQuantity) + inventory, err := scanInventory(row) if err != nil { - return fmt.Errorf("upsert sku inventory %s: %w", formatID(skuID), err) + return nil, fmt.Errorf("upsert sku inventory %s: %w", formatID(skuID), err) } - return nil + return inventory, nil } func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) { @@ -598,12 +720,21 @@ func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs query := fmt.Sprintf(` SELECT pi.id, pi.product_id, + pi.sku_no, pi.name, pi.price, - COALESCE(inv.sold_quantity, 0), pi.attributes, + pi.status, + pi.deleted_at, pi.created_at, - pi.updated_at + pi.updated_at, + inv.id, + inv.sku_id, + inv.available_quantity, + inv.locked_quantity, + inv.sold_quantity, + inv.created_at, + inv.updated_at FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id WHERE pi.product_id IN (%s) @@ -631,52 +762,285 @@ 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 } -func scanProduct(scanner rowScanner) (*ProductRecord, error) { +func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { var ( - rec ProductRecord - id int64 - status int16 - attrsJSON []byte + rec CategoryProductRecord + id int64 + status int16 + imageIDsJSON string ) if err := scanner.Scan( - &id, &rec.SPUNo, &rec.Title, &rec.SellingPoint, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &rec.UpdatedAt, + &rec.CreatedAt, + &rec.Title, + &id, + &rec.SPUNo, + &status, + &imageIDsJSON, + ); err != nil { + return nil, fmt.Errorf("scan category product: %w", err) + } + + rec.ID = formatID(id) + rec.Status = statusFromDB(status) + imageIDs, err := parseStringArrayJSON(imageIDsJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal category product image_ids: %w", err) + } + rec.ImageIDs = imageIDs + 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 + id int64 + brandID sql.NullInt64 + supplierID sql.NullInt64 + imageIDsJSON string + serviceGuaranteesJSON string + goodsType int16 + status int16 + attrsJSON []byte + freightChargeType int16 + freightTemplateID sql.NullInt64 + saleTimeType int16 + scheduledSaleTime sql.NullTime + deletedAt sql.NullTime + ) + if err := scanner.Scan( + &id, + &rec.SPUNo, + &rec.Title, + &rec.SellingPoint, + &brandID, + &supplierID, + &imageIDsJSON, + &rec.DetailHTML, + &rec.MemberDiscountEnabled, + &goodsType, + &serviceGuaranteesJSON, + &status, + &attrsJSON, + &freightChargeType, + &rec.FreightFixedAmount, + &freightTemplateID, + &saleTimeType, + &scheduledSaleTime, + &deletedAt, + &rec.CreatedAt, + &rec.UpdatedAt, ); err != nil { return nil, fmt.Errorf("scan product: %w", err) } rec.ID = formatID(id) + if brandID.Valid { + rec.BrandID = formatID(brandID.Int64) + } + if supplierID.Valid { + rec.SupplierID = formatID(supplierID.Int64) + } + rec.GoodsType = int32(goodsType) + imageIDs, err := parseStringArrayJSON(imageIDsJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal product image_ids: %w", err) + } + rec.ImageIDs = imageIDs + serviceGuarantees, err := parseStringArrayJSON(serviceGuaranteesJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal product service_guarantees: %w", err) + } + rec.ServiceGuarantees = serviceGuarantees rec.Status = statusFromDB(status) + rec.CrossBorderJSON = string(attrsJSON) + if rec.CrossBorderJSON == "" { + rec.CrossBorderJSON = "{}" + } if len(attrsJSON) > 0 { if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil { return nil, fmt.Errorf("unmarshal product attrs: %w", err) } } + if freightTemplateID.Valid { + rec.FreightTemplateID = formatID(freightTemplateID.Int64) + } + rec.FreightChargeType = int32(freightChargeType) + rec.SaleTimeType = int32(saleTimeType) + if scheduledSaleTime.Valid { + rec.ScheduledSaleTime = timePtr(scheduledSaleTime.Time) + } + if deletedAt.Valid { + rec.DeletedAt = timePtr(deletedAt.Time) + } return &rec, nil } func scanSKU(scanner rowScanner) (*SKURecord, error) { var ( - rec SKURecord - id int64 - productID int64 - attrsJSON []byte + rec SKURecord + id int64 + productID int64 + skuNo sql.NullString + attrsJSON []byte + status int16 + deletedAt sql.NullTime + inventoryID sql.NullInt64 + inventorySKUID sql.NullInt64 + availableQuantity sql.NullInt32 + lockedQuantity sql.NullInt32 + soldQuantity sql.NullInt32 + inventoryCreatedAt sql.NullTime + inventoryUpdatedAt sql.NullTime ) if err := scanner.Scan( - &id, &productID, &rec.Name, &rec.Price, &rec.AvailableQuantity, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &id, + &productID, + &skuNo, + &rec.Name, + &rec.Price, + &attrsJSON, + &status, + &deletedAt, + &rec.CreatedAt, + &rec.UpdatedAt, + &inventoryID, + &inventorySKUID, + &availableQuantity, + &lockedQuantity, + &soldQuantity, + &inventoryCreatedAt, + &inventoryUpdatedAt, ); err != nil { return nil, fmt.Errorf("scan sku: %w", err) } rec.ID = formatID(id) rec.ProductID = formatID(productID) + if skuNo.Valid { + rec.SKUNo = skuNo.String + } rec.AttributesJSON = string(attrsJSON) if rec.AttributesJSON == "" { rec.AttributesJSON = "{}" } + rec.Status = int32(status) + if deletedAt.Valid { + rec.DeletedAt = timePtr(deletedAt.Time) + } + if inventoryID.Valid { + rec.Inventory = &InventoryRecord{ + ID: formatID(inventoryID.Int64), + SKUID: formatID(inventorySKUID.Int64), + AvailableQuantity: nullInt32Value(availableQuantity), + LockedQuantity: nullInt32Value(lockedQuantity), + SoldQuantity: nullInt32Value(soldQuantity), + } + if inventoryCreatedAt.Valid { + rec.Inventory.CreatedAt = inventoryCreatedAt.Time + } + if inventoryUpdatedAt.Valid { + rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time + } + rec.AvailableQuantity = rec.Inventory.AvailableQuantity + rec.LockedQuantity = rec.Inventory.LockedQuantity + rec.SoldQuantity = rec.Inventory.SoldQuantity + } + return &rec, nil +} + +func scanInventory(scanner rowScanner) (*InventoryRecord, error) { + var ( + rec InventoryRecord + id int64 + skuID int64 + ) + if err := scanner.Scan( + &id, + &skuID, + &rec.AvailableQuantity, + &rec.LockedQuantity, + &rec.SoldQuantity, + &rec.CreatedAt, + &rec.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan inventory: %w", err) + } + rec.ID = formatID(id) + rec.SKUID = formatID(skuID) return &rec, nil } @@ -686,16 +1050,18 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { id int64 parentID sql.NullInt64 imageJSON []byte + nodeType int16 level int16 status int16 ) if err := scanner.Scan( - &id, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, + &id, &nodeType, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, ); err != nil { return nil, fmt.Errorf("scan category: %w", err) } rec.ID = formatID(id) + rec.NodeType = int32(nodeType) if parentID.Valid { rec.ParentID = formatID(parentID.Int64) } @@ -718,6 +1084,28 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } +func parseStringArrayJSON(raw string) ([]string, error) { + if strings.TrimSpace(raw) == "" { + return []string{}, nil + } + var values []string + if err := json.Unmarshal([]byte(raw), &values); err != nil { + return nil, err + } + return values, nil +} + +func nullInt32Value(value sql.NullInt32) int32 { + if value.Valid { + return value.Int32 + } + return 0 +} + +func timePtr(value time.Time) *time.Time { + return &value +} + func statusToDB(status productv1.ProductStatus) int16 { switch status { case productv1.ProductStatus_PRODUCT_STATUS_DRAFT: diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 314da9b..3e35295 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -7,6 +7,7 @@ import ( "math" "strconv" "strings" + "time" "go.opentelemetry.io/otel/attribute" otelcodes "go.opentelemetry.io/otel/codes" @@ -147,9 +148,9 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) observability.IncCategoryProductLists() - protoProducts := make([]*productv1.Product, 0, len(products)) + protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) for _, product := range products { - protoProducts = append(protoProducts, toProtoProduct(product, skuMap[product.ID])) + protoProducts = append(protoProducts, toProtoCategoryProduct(product, skuMap[product.ID])) } return &productv1.ListCategoryProductsResponse{ @@ -298,25 +299,92 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco protoSKUs = append(protoSKUs, &productv1.SKU{ SkuId: sku.ID, ProductId: sku.ProductID, + SkuNo: sku.SKUNo, Name: sku.Name, Price: sku.Price, AvailableQuantity: sku.AvailableQuantity, + SoldQuantity: sku.SoldQuantity, AttributesJson: sku.AttributesJSON, + Status: sku.Status, + DeletedAt: timestampOrNil(sku.DeletedAt), + CreatedAt: timestamppb.New(sku.CreatedAt), + UpdatedAt: timestamppb.New(sku.UpdatedAt), + Inventory: toProtoInventory(sku.Inventory), }) } return &productv1.Product{ - ProductId: product.ID, - SpuNo: product.SPUNo, - Title: product.Title, - SellingPoint: product.SellingPoint, - Status: product.Status, - Skus: protoSKUs, - CreatedAt: timestamppb.New(product.CreatedAt), - UpdatedAt: timestamppb.New(product.UpdatedAt), + ProductId: product.ID, + SpuNo: product.SPUNo, + Title: product.Title, + SellingPoint: product.SellingPoint, + Status: product.Status, + Skus: protoSKUs, + CreatedAt: timestamppb.New(product.CreatedAt), + UpdatedAt: timestamppb.New(product.UpdatedAt), + ImageIds: product.ImageIDs, + BrandId: product.BrandID, + SupplierId: product.SupplierID, + DetailHtml: product.DetailHTML, + MemberDiscountEnabled: product.MemberDiscountEnabled, + GoodsType: product.GoodsType, + ServiceGuarantees: product.ServiceGuarantees, + CrossBorderJson: product.CrossBorderJSON, + FreightChargeType: product.FreightChargeType, + FreightFixedAmount: product.FreightFixedAmount, + FreightTemplateId: product.FreightTemplateID, + SaleTimeType: product.SaleTimeType, + ScheduledSaleTime: timestampOrNil(product.ScheduledSaleTime), + DeletedAt: timestampOrNil(product.DeletedAt), } } +func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []repository.CategoryProductSKURecord) *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: timestamppb.New(product.UpdatedAt), + CreatedAt: timestamppb.New(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Skus: protoSKUs, + } +} + +func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductItemInventory { + if inventory == nil { + return nil + } + return &productv1.ProductItemInventory{ + InventoryId: inventory.ID, + SkuId: inventory.SKUID, + AvailableQuantity: inventory.AvailableQuantity, + LockedQuantity: inventory.LockedQuantity, + SoldQuantity: inventory.SoldQuantity, + CreatedAt: timestamppb.New(inventory.CreatedAt), + UpdatedAt: timestamppb.New(inventory.UpdatedAt), + } +} + +func timestampOrNil(value *time.Time) *timestamppb.Timestamp { + if value == nil { + return nil + } + return timestamppb.New(*value) +} + func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode { nodes := make(map[string]*productv1.CategoryNode, len(categories)) records := make(map[string]*repository.CategoryRecord, len(categories)) @@ -359,6 +427,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor } return &productv1.CategoryNode{ CategoryId: category.ID, + NodeType: category.NodeType, Name: category.Name, ParentId: category.ParentID, Level: category.Level, From 42419db604fc5de5cd09dd5741452b09e4b3b415 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 13:03:08 +0800 Subject: [PATCH 3/7] =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E5=95=86=E5=93=81=E5=AD=97=E6=AE=B5=E3=80=81SKU=E8=A7=84?= =?UTF-8?q?=E6=A0=BC=E6=95=B4=E7=90=86=E5=92=8C=E5=85=A5=E5=BA=93=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 19 +- internal/repository/product_repository.go | 270 +++++++++++++++++----- internal/server/product_server.go | 208 ++++++++++++++--- scripts/sql/recreate-product-tables.sql | 18 +- 4 files changed, 413 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index 985b402..07d1cb8 100644 --- a/README.md +++ b/README.md @@ -28,24 +28,9 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 ### `CreateProduct` -| 字段 | 类型 | 必填 | 说明 | -|---|---|---|---| -| `product_id` | `string` | 是 | 商品 SPU ID,由调用方生成 | -| `spu_no` | `string` | 是 | SPU 编码,未删除商品内唯一 | -| `title` | `string` | 是 | 商品标题 | -| `selling_point` | `string` | 否 | 商品卖点 | -| `status` | `ProductStatus` | 是 | 商品状态:`DRAFT` / `ON_SALE` / `OFF_SALE` | -| `skus` | `CreateProductSKU[]` | 否 | 创建时附带的 SKU 列表 | +创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 -`CreateProductSKU` 字段: - -| 字段 | 类型 | 必填 | 说明 | -|---|---|---|---| -| `sku_id` | `string` | 是 | SKU ID,由调用方生成 | -| `name` | `string` | 是 | SKU 名称 | -| `price` | `int64` | 是 | 售价,单位:分 | -| `available_quantity` | `int32` | 是 | 初始可售库存 | -| `attributes_json` | `string` | 否 | 规格属性 JSON 字符串 | +当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由数据库生成,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 ### `GetProduct` diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index ce96653..a10cf29 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -40,6 +40,7 @@ type ProductRecord struct { FreightTemplateID string SaleTimeType int32 ScheduledSaleTime *time.Time + LeafCategoryID string DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time @@ -52,10 +53,17 @@ type SKURecord struct { SKUNo string Name string Price int64 + ImageIDs []string AvailableQuantity int32 LockedQuantity int32 SoldQuantity int32 AttributesJSON string + K1 string + V1 string + K2 string + V2 string + K3 string + V3 string Status int32 DeletedAt *time.Time CreatedAt time.Time @@ -118,12 +126,26 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` +CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; + +ALTER TABLE product.products + ALTER COLUMN id SET DEFAULT nextval('product.products_id_seq'); + +ALTER TABLE product.product_category_bindings + ALTER COLUMN id SET DEFAULT nextval('product.product_category_bindings_id_seq'); + +SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); +SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, price BIGINT NOT NULL CHECK (price >= 0), + image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], attributes JSONB NOT NULL DEFAULT '{}', status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), @@ -142,6 +164,11 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); +ALTER TABLE product.product_items + ALTER COLUMN id SET DEFAULT nextval('product.product_items_id_seq'); +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; +SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; @@ -154,40 +181,29 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_ite // CreateProduct inserts a new SPU row. func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRecord) error { - attrs, err := json.Marshal(product.Attrs) - if err != nil { - return fmt.Errorf("marshal product attrs: %w", err) - } - if product.Attrs == nil { - attrs = []byte("{}") - } - - id, err := parseID(product.ID, "product id") + attrs, err := productCrossBorderJSON(product) if err != nil { return err } - _, err = r.db.ExecContext(ctx, ` -INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) -VALUES ($1, $2, $3, $4, $5, $6::jsonb) -`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) + tx, err := r.db.BeginTx(ctx, nil) if err != nil { - return fmt.Errorf("insert product %s: %w", product.ID, err) + return fmt.Errorf("begin create product: %w", err) + } + defer tx.Rollback() + + if _, err := insertProduct(ctx, tx, product, attrs); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit create product: %w", err) } 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") + attrs, err := productCrossBorderJSON(product) if err != nil { return nil, nil, err } @@ -198,20 +214,26 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } defer tx.Rollback() - createdProduct, err := insertProduct(ctx, tx, id, product, attrs) + createdProduct, err := insertProduct(ctx, tx, 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) + createdSKU, err := insertSKU(ctx, tx, createdProduct.ID, sku) if err != nil { return nil, nil, err } createdSKUs = append(createdSKUs, *createdSKU) } + if product.LeafCategoryID != "" { + if err := insertCategoryBinding(ctx, tx, createdProduct.ID, product.LeafCategoryID); err != nil { + return nil, nil, err + } + } + if err := tx.Commit(); err != nil { return nil, nil, fmt.Errorf("commit create product: %w", err) } @@ -293,10 +315,6 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error return err } - id, err := parseID(sku.ID, "sku id") - if err != nil { - return err - } productID, err := parseID(sku.ProductID, "product id") if err != nil { return err @@ -308,12 +326,14 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error } defer tx.Rollback() - _, err = tx.ExecContext(ctx, ` -INSERT INTO product.product_items (id, product_id, name, price, attributes) -VALUES ($1, $2, $3, $4, $5::jsonb) -`, id, productID, sku.Name, sku.Price, attrs) + var id int64 + err = tx.QueryRowContext(ctx, ` +INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) +RETURNING id +`, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&id) if err != nil { - return fmt.Errorf("insert sku %s: %w", sku.ID, err) + return fmt.Errorf("insert sku: %w", err) } if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { @@ -345,9 +365,9 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error res, err := tx.ExecContext(ctx, ` UPDATE product.product_items -SET name = $2, price = $3, attributes = $4::jsonb, updated_at = NOW() +SET sku_no = $2, name = $3, price = $4, image_ids = $5, attributes = $6::jsonb, status = $7, updated_at = NOW() WHERE id = $1 -`, id, sku.Name, sku.Price, attrs) +`, id, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) if err != nil { return fmt.Errorf("update sku %s: %w", sku.ID, err) } @@ -595,10 +615,40 @@ ORDER BY created_at ASC return products, nil } -func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRecord, attrs []byte) (*ProductRecord, error) { +func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) { + brandID, err := nullableID(product.BrandID, "brand_id") + if err != nil { + return nil, err + } + supplierID, err := nullableID(product.SupplierID, "supplier_id") + if err != nil { + return nil, err + } + freightTemplateID, err := nullableID(product.FreightTemplateID, "freight_template_id") + if err != nil { + return nil, err + } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) -VALUES ($1, $2, $3, $4, $5, $6::jsonb) +INSERT INTO product.products ( + spu_no, + title, + selling_point, + brand_id, + supplier_id, + image_ids, + detail_html, + member_discount_enabled, + goods_type, + service_guarantees, + status, + cross_border, + freight_charge_type, + freight_fixed_amount, + freight_template_id, + sale_time_type, + scheduled_sale_time +) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::jsonb, $13, $14, $15, $16, $17) RETURNING id, spu_no, title, @@ -620,11 +670,14 @@ RETURNING id, deleted_at, created_at, updated_at -`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) +`, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), + product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees), + statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, + int16(product.SaleTimeType), product.ScheduledSaleTime) createdProduct, err := scanProduct(row) if err != nil { - return nil, fmt.Errorf("insert product %s: %w", product.ID, err) + return nil, fmt.Errorf("insert product: %w", err) } return createdProduct, nil } @@ -635,23 +688,20 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) 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.product_items (id, product_id, name, price, attributes) -VALUES ($1, $2, $3, $4, $5::jsonb) +INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) RETURNING id, product_id, sku_no, name, price, + COALESCE(to_json(image_ids)::text, '[]'), attributes, status, deleted_at, @@ -664,14 +714,18 @@ RETURNING id, NULL::integer, NULL::timestamptz, NULL::timestamptz -`, id, parsedProductID, sku.Name, sku.Price, attrs) +`, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) createdSKU, err := scanSKU(row) if err != nil { - return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) + return nil, fmt.Errorf("insert sku: %w", err) } - inventory, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity) + createdSKUID, err := parseID(createdSKU.ID, "sku id") + if err != nil { + return nil, err + } + inventory, err := upsertSKUInventory(ctx, tx, createdSKUID, sku.AvailableQuantity) if err != nil { return nil, err } @@ -700,6 +754,27 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create return inventory, nil } +func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryID string) error { + parsedProductID, err := parseID(productID, "product id") + if err != nil { + return err + } + parsedCategoryID, err := parseID(categoryID, "leaf_category_id") + if err != nil { + return err + } + + _, err = tx.ExecContext(ctx, ` +INSERT INTO product.product_category_bindings (product_id, category_id) +VALUES ($1, $2) +ON CONFLICT (product_id, category_id) DO NOTHING +`, parsedProductID, parsedCategoryID) + if err != nil { + return fmt.Errorf("insert category binding: %w", err) + } + return 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 { @@ -723,6 +798,7 @@ SELECT pi.id, pi.sku_no, pi.name, pi.price, + COALESCE(to_json(pi.image_ids)::text, '[]'), pi.attributes, pi.status, pi.deleted_at, @@ -955,6 +1031,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { id int64 productID int64 skuNo sql.NullString + imageIDsJSON string attrsJSON []byte status int16 deletedAt sql.NullTime @@ -972,6 +1049,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { &skuNo, &rec.Name, &rec.Price, + &imageIDsJSON, &attrsJSON, &status, &deletedAt, @@ -993,9 +1071,17 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { if skuNo.Valid { rec.SKUNo = skuNo.String } + imageIDs, err := parseStringArrayJSON(imageIDsJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal sku image_ids: %w", err) + } + rec.ImageIDs = imageIDs rec.AttributesJSON = string(attrsJSON) if rec.AttributesJSON == "" { - rec.AttributesJSON = "{}" + rec.AttributesJSON = "[]" + } + if err := applySKUAttributes(&rec); err != nil { + return nil, err } rec.Status = int32(status) if deletedAt.Valid { @@ -1076,7 +1162,7 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { func normalizeAttributesJSON(raw string) ([]byte, error) { if strings.TrimSpace(raw) == "" { - return []byte("{}"), nil + return []byte("[]"), nil } if !json.Valid([]byte(raw)) { return nil, fmt.Errorf("invalid attributes json: %s", raw) @@ -1084,6 +1170,58 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } +func productCrossBorderJSON(product ProductRecord) ([]byte, error) { + if strings.TrimSpace(product.CrossBorderJSON) != "" { + attrs := []byte(product.CrossBorderJSON) + if !json.Valid(attrs) { + return nil, fmt.Errorf("invalid cross_border_json") + } + return attrs, nil + } + attrs, err := json.Marshal(product.Attrs) + if err != nil { + return nil, fmt.Errorf("marshal product attrs: %w", err) + } + if product.Attrs == nil { + attrs = []byte("{}") + } + return attrs, nil +} + +func applySKUAttributes(rec *SKURecord) error { + if rec == nil || strings.TrimSpace(rec.AttributesJSON) == "" { + return nil + } + if strings.TrimSpace(rec.AttributesJSON) == "{}" { + return nil + } + var attrs []map[string]string + if err := json.Unmarshal([]byte(rec.AttributesJSON), &attrs); err != nil { + return fmt.Errorf("unmarshal sku attributes: %w", err) + } + for _, item := range attrs { + if value := item["k1"]; value != "" { + rec.K1 = value + } + if value := item["v1"]; value != "" { + rec.V1 = value + } + if value := item["k2"]; value != "" { + rec.K2 = value + } + if value := item["v2"]; value != "" { + rec.V2 = value + } + if value := item["k3"]; value != "" { + rec.K3 = value + } + if value := item["v3"]; value != "" { + rec.V3 = value + } + } + return nil +} + func parseStringArrayJSON(raw string) ([]string, error) { if strings.TrimSpace(raw) == "" { return []string{}, nil @@ -1095,6 +1233,32 @@ func parseStringArrayJSON(raw string) ([]string, error) { return values, nil } +func nullableID(raw, field string) (sql.NullInt64, error) { + if strings.TrimSpace(raw) == "" { + return sql.NullInt64{}, nil + } + id, err := parseID(raw, field) + if err != nil { + return sql.NullInt64{}, err + } + return sql.NullInt64{Int64: id, Valid: true}, nil +} + +func nullString(raw string) sql.NullString { + value := strings.TrimSpace(raw) + if value == "" { + return sql.NullString{} + } + return sql.NullString{String: value, Valid: true} +} + +func stringSliceOrEmpty(values []string) []string { + if values == nil { + return []string{} + } + return values +} + func nullInt32Value(value sql.NullInt32) int32 { if value.Valid { return value.Int32 diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3e35295..9b3af7e 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -15,6 +15,7 @@ import ( "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/timestamppb" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" @@ -64,7 +65,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( - attribute.String("product.id", product.ID), + attribute.String("product.spu_no", product.SPUNo), attribute.Int("product.sku_count", len(skus)), )) defer dbSpan.End() @@ -73,7 +74,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) - s.observer.Logger(ctx).Error("create product failed", zap.String("product_id", product.ID), zap.Error(err)) + s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err)) return nil, status.Errorf(codes.Internal, "create product: %v", err) } observability.IncProductsCreated() @@ -201,11 +202,6 @@ func totalPages(total int64, pageSize int32) int32 { } func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) { - productID := strings.TrimSpace(req.GetProductId()) - if err := validatePositiveID(productID, "product_id"); err != nil { - return repository.ProductRecord{}, nil, err - } - spuNo := strings.TrimSpace(req.GetSpuNo()) if spuNo == "" { return repository.ProductRecord{}, nil, errors.New("spu_no is required") @@ -220,19 +216,53 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT } + crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo()) + if err != nil { + return repository.ProductRecord{}, nil, err + } record := repository.ProductRecord{ - ID: productID, - SPUNo: spuNo, - Title: title, - SellingPoint: req.GetSellingPoint(), - Status: statusValue, - Attrs: map[string]any{}, + SPUNo: spuNo, + Title: title, + SellingPoint: strings.TrimSpace(req.GetSellingPoint()), + BrandID: strings.TrimSpace(req.GetBrandId()), + SupplierID: strings.TrimSpace(req.GetSupplierId()), + ImageIDs: normalizeStringList(req.GetImageIds()), + DetailHTML: req.GetDetailHtml(), + MemberDiscountEnabled: req.GetMemberDiscountEnabled(), + GoodsType: defaultInt32(req.GetGoodsType(), 1), + ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()), + Status: statusValue, + CrossBorderJSON: crossBorderJSON, + FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1), + FreightFixedAmount: req.GetFreightFixedAmount(), + FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), + SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), + ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), + LeafCategoryID: strings.TrimSpace(req.GetLeafCategoryId()), + } + if record.FreightFixedAmount < 0 { + return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0") + } + if record.GoodsType < 1 || record.GoodsType > 4 { + return repository.ProductRecord{}, nil, errors.New("goods_type must be between 1 and 4") + } + if record.FreightChargeType < 1 || record.FreightChargeType > 2 { + return repository.ProductRecord{}, nil, errors.New("freight_charge_type must be 1 or 2") + } + if record.FreightChargeType == 2 && record.FreightTemplateID == "" { + return repository.ProductRecord{}, nil, errors.New("freight_template_id is required when freight_charge_type is 2") + } + if record.SaleTimeType < 1 || record.SaleTimeType > 2 { + return repository.ProductRecord{}, nil, errors.New("sale_time_type must be 1 or 2") + } + if record.SaleTimeType == 2 && record.ScheduledSaleTime == nil { + return repository.ProductRecord{}, nil, errors.New("scheduled_sale_time is required when sale_time_type is 2") } skus := make([]repository.SKURecord, 0, len(req.GetSkus())) for i, protoSKU := range req.GetSkus() { - sku, err := skuFromCreateInput(productID, protoSKU) + sku, err := skuFromCreateInput(protoSKU) if err != nil { return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) } @@ -242,20 +272,11 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P return record, skus, nil } -func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repository.SKURecord, error) { +func skuFromCreateInput(sku *productv1.CreateProductSKU) (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 - } - - 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") } @@ -263,21 +284,142 @@ func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repo return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0") } - attrs := strings.TrimSpace(sku.GetAttributesJson()) - if attrs != "" && !json.Valid([]byte(attrs)) { - return repository.SKURecord{}, errors.New("attributes_json must be valid json") + attrs, name, err := buildSKUAttributesAndName(sku) + if err != nil { + return repository.SKURecord{}, err + } + statusValue := sku.GetStatus() + if statusValue == 0 { + statusValue = 1 + } + if statusValue < 0 || statusValue > 1 { + return repository.SKURecord{}, errors.New("status must be 0 or 1") } return repository.SKURecord{ - ID: skuID, - ProductID: productID, + SKUNo: strings.TrimSpace(sku.GetSkuNo()), Name: name, Price: sku.GetPrice(), + ImageIDs: normalizeStringList(sku.GetImageIds()), AvailableQuantity: sku.GetAvailableQuantity(), AttributesJSON: attrs, + K1: strings.TrimSpace(sku.GetK1()), + V1: strings.TrimSpace(sku.GetV1()), + K2: strings.TrimSpace(sku.GetK2()), + V2: strings.TrimSpace(sku.GetV2()), + K3: strings.TrimSpace(sku.GetK3()), + V3: strings.TrimSpace(sku.GetV3()), + Status: statusValue, }, nil } +func buildSKUAttributesAndName(sku *productv1.CreateProductSKU) (string, string, error) { + specs := []struct { + keyField string + valueField string + key string + value string + }{ + {keyField: "k1", valueField: "v1", key: strings.TrimSpace(sku.GetK1()), value: strings.TrimSpace(sku.GetV1())}, + {keyField: "k2", valueField: "v2", key: strings.TrimSpace(sku.GetK2()), value: strings.TrimSpace(sku.GetV2())}, + {keyField: "k3", valueField: "v3", key: strings.TrimSpace(sku.GetK3()), value: strings.TrimSpace(sku.GetV3())}, + } + + attrs := make([]map[string]string, 0, len(specs)) + nameParts := make([]string, 0, len(specs)) + foundEmpty := false + for _, spec := range specs { + if spec.key == "" && spec.value == "" { + foundEmpty = true + continue + } + if foundEmpty { + return "", "", errors.New("sku specs must be filled in order from k1/v1 to k3/v3") + } + if spec.key == "" || spec.value == "" { + return "", "", errors.New(spec.keyField + "/" + spec.valueField + " must be provided together") + } + attrs = append(attrs, map[string]string{ + spec.keyField: spec.key, + spec.valueField: spec.value, + }) + nameParts = append(nameParts, spec.value) + } + if len(attrs) == 0 { + return "", "", errors.New("at least one sku spec k1/v1 is required") + } + + attrsJSON, err := json.Marshal(attrs) + if err != nil { + return "", "", err + } + return string(attrsJSON), strings.Join(nameParts, " "), nil +} + +func crossBorderJSONFromProto(info *productv1.CrossBorderInfo) (string, error) { + if info == nil { + return "{}", nil + } + if info.GetCustomsTaxRateBps() < 0 { + return "", errors.New("cross_border_info.customs_tax_rate_bps must be greater than or equal to 0") + } + switch info.GetLogisticsMode() { + case productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_UNSPECIFIED, + productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_BONDED_IMPORT, + productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_OVERSEAS_DIRECT_MAIL: + default: + return "", errors.New("cross_border_info.logistics_mode is invalid") + } + + marshalOptions := protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true} + raw, err := marshalOptions.Marshal(info) + if err != nil { + return "", err + } + return string(raw), nil +} + +func toProtoCrossBorderInfo(raw string) *productv1.CrossBorderInfo { + if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" { + return nil + } + info := &productv1.CrossBorderInfo{} + unmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true} + if err := unmarshalOptions.Unmarshal([]byte(raw), info); err != nil { + return nil + } + return info +} + +func normalizeStringList(values []string) []string { + if len(values) == 0 { + return []string{} + } + out := make([]string, 0, len(values)) + for _, value := range values { + trimmed := strings.TrimSpace(value) + if trimmed != "" { + out = append(out, trimmed) + } + } + return out +} + +func defaultInt32(value, fallback int32) int32 { + if value == 0 { + return fallback + } + return value +} + +func timestampToTime(value *timestamppb.Timestamp) *time.Time { + if value == nil { + return nil + } + t := value.AsTime() + return &t +} + func validatePositiveID(raw, field string) error { if raw == "" { return errors.New(field + " is required") @@ -306,6 +448,13 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco SoldQuantity: sku.SoldQuantity, AttributesJson: sku.AttributesJSON, Status: sku.Status, + ImageIds: sku.ImageIDs, + K1: sku.K1, + V1: sku.V1, + K2: sku.K2, + V2: sku.V2, + K3: sku.K3, + V3: sku.V3, DeletedAt: timestampOrNil(sku.DeletedAt), CreatedAt: timestamppb.New(sku.CreatedAt), UpdatedAt: timestamppb.New(sku.UpdatedAt), @@ -330,6 +479,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco GoodsType: product.GoodsType, ServiceGuarantees: product.ServiceGuarantees, CrossBorderJson: product.CrossBorderJSON, + CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), FreightChargeType: product.FreightChargeType, FreightFixedAmount: product.FreightFixedAmount, FreightTemplateId: product.FreightTemplateID, diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 34ac606..44490fc 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -27,6 +27,10 @@ CREATE EXTENSION IF NOT EXISTS "pg_trgm"; CREATE SCHEMA IF NOT EXISTS product; +CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; + CREATE OR REPLACE FUNCTION public.set_updated_at() RETURNS TRIGGER AS $$ BEGIN @@ -36,7 +40,7 @@ END; $$ LANGUAGE plpgsql; CREATE TABLE IF NOT EXISTS product.products ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.products_id_seq'), spu_no VARCHAR(100) NOT NULL, title VARCHAR(200) NOT NULL, selling_point VARCHAR(300), @@ -105,6 +109,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no ON product.products (spu_no) WHERE deleted_at IS NULL; +SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_category ( id BIGINT PRIMARY KEY, node_type SMALLINT NOT NULL DEFAULT 0, @@ -139,7 +145,7 @@ CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort ON product.product_category (node_type, status, sort_num); CREATE TABLE IF NOT EXISTS product.product_category_bindings ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.product_category_bindings_id_seq'), product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE, CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id) @@ -153,12 +159,15 @@ COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类 CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id ON product.product_category_bindings (category_id); +SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, price BIGINT NOT NULL CHECK (price >= 0), + image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], attributes JSONB NOT NULL DEFAULT '{}', status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), @@ -169,6 +178,7 @@ CREATE TABLE IF NOT EXISTS product.product_items ( COMMENT ON TABLE product.product_items IS '商品 SKU 明细表:存储具体可售规格、价格和规格属性;库存统一存储在 product.product_item_inventory'; COMMENT ON COLUMN product.product_items.price IS 'SKU 售价,单位:分'; +COMMENT ON COLUMN product.product_items.image_ids IS 'SKU 图片 ID 列表'; COMMENT ON COLUMN product.product_items.attributes IS 'SKU 规格属性 JSONB,如颜色、尺寸等'; COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用'; COMMENT ON COLUMN product.product_items.version IS 'SKU 乐观锁版本号'; @@ -186,6 +196,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items (sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; +SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, From 517f629d76a82c28d25dd344c632cc4b1923ee33 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Fri, 10 Jul 2026 15:56:42 +0800 Subject: [PATCH 4/7] feat: integrate Snowflake ID generation for product and SKU creation - Added a new ID generator using the Snowflake algorithm to create unique identifiers for products and SKUs. - Updated the product server to utilize the ID generator for assigning IDs during product and SKU creation. - Refactored the product repository to accommodate the new ID handling logic. - Introduced unit tests for the ID generator to ensure correct functionality and error handling. --- cmd/main.go | 8 ++++- go.mod | 1 + go.sum | 2 ++ internal/idgen/snowflake.go | 41 +++++++++++++++++++++++ internal/idgen/snowflake_test.go | 28 ++++++++++++++++ internal/repository/product_repository.go | 32 ++++++++++++------ internal/server/product_server.go | 12 ++++++- 7 files changed, 112 insertions(+), 12 deletions(-) create mode 100644 internal/idgen/snowflake.go create mode 100644 internal/idgen/snowflake_test.go diff --git a/cmd/main.go b/cmd/main.go index 7ef9e39..423fa95 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -20,6 +20,7 @@ import ( productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/config" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/server" @@ -70,6 +71,11 @@ func main() { logger.Fatal("ensure product schema failed", zap.Error(err)) } + idGenerator, err := idgen.NewFromEnv() + if err != nil { + logger.Fatal("init snowflake id generator failed", zap.Error(err)) + } + metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext) go func() { logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort)) @@ -79,7 +85,7 @@ func main() { } }() - productServer := server.NewProductServer(repo, logger, observer) + productServer := server.NewProductServer(repo, idGenerator, logger, observer) grpcServer := grpc.NewServer( grpc.StatsHandler(otelgrpc.NewServerHandler()), diff --git a/go.mod b/go.mod index e25a1df..72fadc2 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.26.4 replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto require ( + github.com/bwmarrin/snowflake v0.3.0 github.com/jackc/pgx/v5 v5.10.0 github.com/joho/godotenv v1.5.1 github.com/prometheus/client_golang v1.23.2 diff --git a/go.sum b/go.sum index bd7c6d0..fae7067 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0= +github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= diff --git a/internal/idgen/snowflake.go b/internal/idgen/snowflake.go new file mode 100644 index 0000000..9ed90e4 --- /dev/null +++ b/internal/idgen/snowflake.go @@ -0,0 +1,41 @@ +package idgen + +import ( + "fmt" + "os" + "strconv" + + "github.com/bwmarrin/snowflake" +) + +// Generator creates 64-bit, time-sortable Snowflake IDs. +type Generator struct { + node *snowflake.Node +} + +// NewFromEnv creates a generator using SNOWFLAKE_WORKER_ID, defaulting to 1. +func NewFromEnv() (*Generator, error) { + workerID := int64(1) + if raw := os.Getenv("SNOWFLAKE_WORKER_ID"); raw != "" { + parsed, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + return nil, fmt.Errorf("parse SNOWFLAKE_WORKER_ID: %w", err) + } + workerID = parsed + } + node, err := snowflake.NewNode(workerID) + if err != nil { + return nil, fmt.Errorf("create snowflake node: %w", err) + } + return &Generator{node: node}, nil +} + +// Next returns a new Snowflake ID. +func (g *Generator) Next() int64 { + return g.node.Generate().Int64() +} + +// NextString returns a decimal string representation of Next. +func (g *Generator) NextString() string { + return strconv.FormatInt(g.Next(), 10) +} diff --git a/internal/idgen/snowflake_test.go b/internal/idgen/snowflake_test.go new file mode 100644 index 0000000..2f42d95 --- /dev/null +++ b/internal/idgen/snowflake_test.go @@ -0,0 +1,28 @@ +package idgen + +import ( + "strconv" + "testing" +) + +func TestGeneratorNextString(t *testing.T) { + t.Setenv("SNOWFLAKE_WORKER_ID", "1") + + g, err := NewFromEnv() + if err != nil { + t.Fatalf("NewFromEnv() error = %v", err) + } + + id := g.NextString() + if _, err := strconv.ParseInt(id, 10, 64); err != nil { + t.Fatalf("NextString() = %q, want decimal int64: %v", id, err) + } +} + +func TestNewFromEnvRejectsInvalidWorkerID(t *testing.T) { + t.Setenv("SNOWFLAKE_WORKER_ID", "1024") + + if _, err := NewFromEnv(); err == nil { + t.Fatal("NewFromEnv() error = nil, want error") + } +} diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index a10cf29..c9e55ad 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -319,6 +319,10 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error if err != nil { return err } + skuID, err := parseID(sku.ID, "sku id") + if err != nil { + return err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { @@ -326,17 +330,16 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error } defer tx.Rollback() - var id int64 err = tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) -VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) +INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8) RETURNING id -`, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&id) +`, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID) if err != nil { return fmt.Errorf("insert sku: %w", err) } - if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := upsertSKUInventory(ctx, tx, skuID, sku.AvailableQuantity); err != nil { return err } @@ -616,6 +619,10 @@ ORDER BY created_at ASC } func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) { + id, err := parseID(product.ID, "product id") + if err != nil { + return nil, err + } brandID, err := nullableID(product.BrandID, "brand_id") if err != nil { return nil, err @@ -630,6 +637,7 @@ func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs } row := tx.QueryRowContext(ctx, ` INSERT INTO product.products ( + id, spu_no, title, selling_point, @@ -648,7 +656,7 @@ INSERT INTO product.products ( sale_time_type, scheduled_sale_time ) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::jsonb, $13, $14, $15, $16, $17) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18) RETURNING id, spu_no, title, @@ -670,7 +678,7 @@ RETURNING id, deleted_at, created_at, updated_at -`, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), +`, id, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees), statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, int16(product.SaleTimeType), product.ScheduledSaleTime) @@ -687,6 +695,10 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) 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 { @@ -694,8 +706,8 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) -VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) +INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8) RETURNING id, product_id, sku_no, @@ -714,7 +726,7 @@ RETURNING id, NULL::integer, NULL::timestamptz, NULL::timestamptz -`, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) +`, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) createdSKU, err := scanSKU(row) if err != nil { diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 9b3af7e..3b262c7 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -20,6 +20,7 @@ import ( productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" ) @@ -34,12 +35,13 @@ type ProductServer struct { productv1.UnimplementedProductServiceServer repo *repository.ProductRepository + idgen *idgen.Generator logger *zap.Logger observer *observability.Observer } // NewProductServer constructs the gRPC product service handler. -func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, observer *observability.Observer) *ProductServer { +func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer { if logger == nil { logger = zap.NewNop() } @@ -48,6 +50,7 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, ob } return &ProductServer{ repo: repo, + idgen: idGenerator, logger: logger, observer: observer, } @@ -63,6 +66,13 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + product.ID = s.idgen.NextString() + for i := range skus { + skus[i].ID = s.idgen.NextString() + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( attribute.String("product.spu_no", product.SPUNo), From 1c89c4a11fe8881980a0a13dca0a214067b89368 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 16:31:07 +0800 Subject: [PATCH 5/7] feat(product): switch product IDs to application snowflake generation --- .env.example | 1 + README.md | 56 +++++++++++++++++++++-- cmd/main.go | 10 ++-- docker-compose.yaml | 1 + internal/repository/product_repository.go | 31 ++++++------- internal/server/product_server.go | 3 ++ scripts/sql/recreate-product-tables.sql | 16 ++----- 7 files changed, 80 insertions(+), 38 deletions(-) diff --git a/.env.example b/.env.example index f804ea9..1d7d2e1 100644 --- a/.env.example +++ b/.env.example @@ -12,6 +12,7 @@ METRICS_PORT=:9102 OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 OTEL_EXPORTER_OTLP_INSECURE=true DEPLOYMENT_ENVIRONMENT=development +SNOWFLAKE_WORKER_ID=1 # Optional # POSTGRES_DSN=postgres://... # full DSN override (skips assembly above) diff --git a/README.md b/README.md index 07d1cb8..de22173 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,56 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 -当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由数据库生成,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 +当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 + +创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成: + +| ID | 生成方式 | 写入位置 | +|---|---|---| +| `product_id` | 服务内 Snowflake 生成 | `product.products.id` | +| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` | +| `inventory_id` | 复用对应 `sku_id` | `product.product_item_inventory.id` | +| 分类绑定 ID | 传入 `leaf_category_id` 时服务内 Snowflake 生成 | `product.product_category_bindings.id` | + +常用请求字段: + +| 字段 | 必填 | 说明 | +|---|---:|---| +| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 | +| `title` | 是 | 商品标题 | +| `selling_point` | 否 | 商品卖点 | +| `leaf_category_id` | 否 | 已存在的分类/分组节点 ID;传入后会写入分类绑定 | +| `image_ids` | 否 | 商品图片 ID 列表 | +| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID | +| `status` | 否 | 未传时默认草稿 | +| `goods_type` | 否 | 未传时默认 `1` | +| `freight_charge_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `freight_template_id` | +| `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` | +| `skus` | 否 | SKU 列表 | + +`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 名称由规格值拼接,例如 `500g 原味`。 + +最小示例: + +```json +{ + "spu_no": "SPU202607100001", + "title": "澳洲和牛家庭装", + "selling_point": "原切谷饲,冷链到家", + "leaf_category_id": "726390485721088000", + "skus": [ + { + "sku_no": "SKU20260710000101", + "price": 12800, + "available_quantity": 100, + "k1": "规格", + "v1": "1kg" + } + ] +} +``` + +响应中的 `product.product_id` 和 `product.skus[].sku_id` 是服务生成后的最终主键 ID。 ### `GetProduct` @@ -137,6 +186,7 @@ cp .env.example .env | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址 | | `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接 | | `DEPLOYMENT_ENVIRONMENT` | `development` | Trace resource 中的部署环境标签 | +| `SNOWFLAKE_WORKER_ID` | `1` | Snowflake worker ID;同一部署环境内不同服务实例必须使用不同值 | ### 可观测性 @@ -170,8 +220,8 @@ grpcurl -plaintext localhost:50052 list grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct -# 创建商品 -grpcurl -plaintext -d '{"product_id":"","spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ +# 创建商品;product_id 和 sku_id 由服务生成 +grpcurl -plaintext -d '{"spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ localhost:50052 ids.product.v1.ProductService/CreateProduct # 分页查询分类商品 diff --git a/cmd/main.go b/cmd/main.go index 423fa95..69499ab 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -38,6 +38,11 @@ func main() { logger.Fatal("load config failed", zap.Error(err)) } + idGenerator, err := idgen.NewFromEnv() + if err != nil { + logger.Fatal("init snowflake id generator failed", zap.Error(err)) + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() @@ -71,11 +76,6 @@ func main() { logger.Fatal("ensure product schema failed", zap.Error(err)) } - idGenerator, err := idgen.NewFromEnv() - if err != nil { - logger.Fatal("init snowflake id generator failed", zap.Error(err)) - } - metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext) go func() { logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort)) diff --git a/docker-compose.yaml b/docker-compose.yaml index 124536c..c65f107 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -20,6 +20,7 @@ services: OTEL_EXPORTER_OTLP_ENDPOINT: http://ids-tempo:4318 OTEL_EXPORTER_OTLP_INSECURE: "true" DEPLOYMENT_ENVIRONMENT: ${DEPLOYMENT_ENVIRONMENT:-development} + SNOWFLAKE_WORKER_ID: ${SNOWFLAKE_WORKER_ID:-1} GOMODCACHE: /go/pkg/mod GOCACHE: /root/.cache/go-build ports: diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index c9e55ad..59e44c4 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -41,6 +41,7 @@ type ProductRecord struct { SaleTimeType int32 ScheduledSaleTime *time.Time LeafCategoryID string + CategoryBindingID string DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time @@ -126,21 +127,14 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` -CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; - ALTER TABLE product.products - ALTER COLUMN id SET DEFAULT nextval('product.products_id_seq'); + ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_category_bindings - ALTER COLUMN id SET DEFAULT nextval('product.product_category_bindings_id_seq'); - -SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); -SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); + ALTER COLUMN id DROP DEFAULT; CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), + id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, @@ -165,10 +159,9 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); ALTER TABLE product.product_items - ALTER COLUMN id SET DEFAULT nextval('product.product_items_id_seq'); + ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; -SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; @@ -229,7 +222,7 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } if product.LeafCategoryID != "" { - if err := insertCategoryBinding(ctx, tx, createdProduct.ID, product.LeafCategoryID); err != nil { + if err := insertCategoryBinding(ctx, tx, product.CategoryBindingID, createdProduct.ID, product.LeafCategoryID); err != nil { return nil, nil, err } } @@ -766,7 +759,11 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create return inventory, nil } -func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryID string) error { +func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID, categoryID string) error { + parsedBindingID, err := parseID(bindingID, "category binding id") + if err != nil { + return err + } parsedProductID, err := parseID(productID, "product id") if err != nil { return err @@ -777,10 +774,10 @@ func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryI } _, err = tx.ExecContext(ctx, ` -INSERT INTO product.product_category_bindings (product_id, category_id) -VALUES ($1, $2) +INSERT INTO product.product_category_bindings (id, product_id, category_id) +VALUES ($1, $2, $3) ON CONFLICT (product_id, category_id) DO NOTHING -`, parsedProductID, parsedCategoryID) +`, parsedBindingID, parsedProductID, parsedCategoryID) if err != nil { return fmt.Errorf("insert category binding: %w", err) } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3b262c7..3a5cfaf 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -73,6 +73,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create for i := range skus { skus[i].ID = s.idgen.NextString() } + if product.LeafCategoryID != "" { + product.CategoryBindingID = s.idgen.NextString() + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( attribute.String("product.spu_no", product.SPUNo), diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 44490fc..43a2173 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -27,10 +27,6 @@ CREATE EXTENSION IF NOT EXISTS "pg_trgm"; CREATE SCHEMA IF NOT EXISTS product; -CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; - CREATE OR REPLACE FUNCTION public.set_updated_at() RETURNS TRIGGER AS $$ BEGIN @@ -40,7 +36,7 @@ END; $$ LANGUAGE plpgsql; CREATE TABLE IF NOT EXISTS product.products ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.products_id_seq'), + id BIGINT PRIMARY KEY, spu_no VARCHAR(100) NOT NULL, title VARCHAR(200) NOT NULL, selling_point VARCHAR(300), @@ -109,8 +105,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no ON product.products (spu_no) WHERE deleted_at IS NULL; -SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_category ( id BIGINT PRIMARY KEY, node_type SMALLINT NOT NULL DEFAULT 0, @@ -145,7 +139,7 @@ CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort ON product.product_category (node_type, status, sort_num); CREATE TABLE IF NOT EXISTS product.product_category_bindings ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_category_bindings_id_seq'), + id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE, CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id) @@ -159,10 +153,8 @@ COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类 CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id ON product.product_category_bindings (category_id); -SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), + id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, @@ -196,8 +188,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items (sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; -SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, From d0f0aea15f4b0b9f826aa4a94a33ca64ccc5d5f0 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 17:29:04 +0800 Subject: [PATCH 6/7] feat(product): return compact create product result --- README.md | 16 +++++++++++++++- internal/server/product_server.go | 18 ++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index de22173..3ff3888 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,21 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 } ``` -响应中的 `product.product_id` 和 `product.skus[].sku_id` 是服务生成后的最终主键 ID。 +响应只返回创建结果摘要,字段结构如下: + +```json +{ + "data": { + "item_id": 726390485721088000, + "title": "澳洲和牛家庭装" + }, + "success": true, + "code": 0, + "message": "success" +} +``` + +其中 `data.item_id` 是服务生成后的商品主键 ID,`data.title` 是商品标题。 ### `GetProduct` diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3a5cfaf..6887b5e 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -83,7 +83,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create )) defer dbSpan.End() - createdProduct, createdSKUs, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus) + createdProduct, _, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -92,8 +92,22 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create } observability.IncProductsCreated() + itemID, err := strconv.ParseInt(createdProduct.ID, 10, 64) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("parse created product id failed", zap.String("product_id", createdProduct.ID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "parse created product id: %v", err) + } + return &productv1.CreateProductResponse{ - Product: toProtoProduct(createdProduct, createdSKUs), + Data: &productv1.CreateProductData{ + ItemId: itemID, + Title: createdProduct.Title, + }, + Success: true, + Code: 0, + Message: "success", }, nil } From 2fa8872603268fc4ca45885389b619dfa158708d Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 19:04:45 +0800 Subject: [PATCH 7/7] fix(product): tighten SKU attributes parsing for product query --- internal/repository/product_repository.go | 63 ++++++++++++++++++++--- internal/server/product_server.go | 3 ++ 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 59e44c4..08e99d4 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -10,6 +10,8 @@ import ( "strings" "time" + "github.com/jackc/pgx/v5/pgconn" + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" ) @@ -19,6 +21,9 @@ var ErrProductNotFound = errors.New("product not found") // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") +// ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number. +var ErrDuplicateSPUNo = errors.New("spu_no already exists") + // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { ID string @@ -678,11 +683,22 @@ RETURNING id, createdProduct, err := scanProduct(row) if err != nil { + if isPostgresConstraintError(err, "23505", "uq_products_spu_no") { + return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, product.SPUNo) + } return nil, fmt.Errorf("insert product: %w", err) } return createdProduct, nil } +func isPostgresConstraintError(err error, code, constraint string) bool { + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) { + return false + } + return pgErr.Code == code && pgErr.ConstraintName == constraint +} + func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) { attrs, err := normalizeAttributesJSON(sku.AttributesJSON) if err != nil { @@ -1198,15 +1214,12 @@ func productCrossBorderJSON(product ProductRecord) ([]byte, error) { } func applySKUAttributes(rec *SKURecord) error { - if rec == nil || strings.TrimSpace(rec.AttributesJSON) == "" { + if rec == nil { return nil } - if strings.TrimSpace(rec.AttributesJSON) == "{}" { - return nil - } - var attrs []map[string]string - if err := json.Unmarshal([]byte(rec.AttributesJSON), &attrs); err != nil { - return fmt.Errorf("unmarshal sku attributes: %w", err) + attrs, err := parseSKUAttributes(rec.AttributesJSON) + if err != nil { + return err } for _, item := range attrs { if value := item["k1"]; value != "" { @@ -1231,6 +1244,42 @@ func applySKUAttributes(rec *SKURecord) error { return nil } +func parseSKUAttributes(raw string) ([]map[string]string, error) { + raw = strings.TrimSpace(raw) + if raw == "" || raw == "{}" || raw == "null" { + return nil, nil + } + var attrs []map[string]string + if err := json.Unmarshal([]byte(raw), &attrs); err == nil { + return attrs, nil + } + + var attr map[string]any + if err := json.Unmarshal([]byte(raw), &attr); err != nil { + return nil, fmt.Errorf("unmarshal sku attributes: %w", err) + } + if isEmptySKUAttributeObject(attr) { + return nil, nil + } + return nil, fmt.Errorf("unmarshal sku attributes: expected array, got object") +} + +func isEmptySKUAttributeObject(attr map[string]any) bool { + if len(attr) == 0 { + return true + } + for _, value := range attr { + if value == nil { + continue + } + if s, ok := value.(string); ok && strings.TrimSpace(s) == "" { + continue + } + return false + } + return true +} + func parseStringArrayJSON(raw string) ([]string, error) { if strings.TrimSpace(raw) == "" { return []string{}, nil diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 6887b5e..29716c1 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -88,6 +88,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err)) + if errors.Is(err, repository.ErrDuplicateSPUNo) { + return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo) + } return nil, status.Errorf(codes.Internal, "create product: %v", err) } observability.IncProductsCreated()