diff --git a/README.md b/README.md index 54c47c2..3a05c0b 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 -当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 +当前创建接口不再接收 `product_id`、`sku_id`、`inventory_id` 和 SKU `name`:`product_id`、`sku_id`、`inventory_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成: @@ -38,7 +38,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 |---|---|---| | `product_id` | 服务内 Snowflake 生成 | `product.products.id` | | `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` | -| `inventory_id` | 复用对应 `sku_id` | `product.product_item_inventory.id` | +| `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` | | 分类绑定 ID | 传入 `leaf_category_id` 时服务内 Snowflake 生成 | `product.product_category_bindings.id` | 常用请求字段: diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 08e99d4..04b2159 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -239,6 +239,57 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P return createdProduct, createdSKUs, nil } +// CreateCategoryTree inserts a top-level category and its optional child categories in one transaction. +func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent CategoryRecord, children []CategoryRecord) (*CategoryRecord, []*CategoryRecord, error) { + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, nil, fmt.Errorf("begin create category tree: %w", err) + } + defer tx.Rollback() + + createdParent, err := insertCategoryNode(ctx, tx, parent) + if err != nil { + return nil, nil, err + } + + createdChildren := make([]*CategoryRecord, 0, len(children)) + for _, child := range children { + child.NodeType = createdParent.NodeType + child.ParentID = createdParent.ID + child.Level = createdParent.Level + 1 + + createdChild, err := insertCategoryNode(ctx, tx, child) + if err != nil { + return nil, nil, err + } + createdChildren = append(createdChildren, createdChild) + } + + if err := tx.Commit(); err != nil { + return nil, nil, fmt.Errorf("commit create category tree: %w", err) + } + + return createdParent, createdChildren, nil +} + +// CreateCategoryNode inserts a single product category/group node. +func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category CategoryRecord) (*CategoryRecord, error) { + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin create category node: %w", err) + } + defer tx.Rollback() + + createdCategory, err := insertCategoryNode(ctx, tx, category) + if err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit create category node: %w", err) + } + return createdCategory, nil +} + // UpdateProduct updates mutable SPU fields. func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error { attrs, err := json.Marshal(product.Attrs) @@ -321,6 +372,10 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error if err != nil { return err } + inventoryID, err := inventoryIDFromSKU(sku) + if err != nil { + return err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { @@ -337,7 +392,7 @@ RETURNING id return fmt.Errorf("insert sku: %w", err) } - if _, err := upsertSKUInventory(ctx, tx, skuID, sku.AvailableQuantity); err != nil { + if _, err := upsertSKUInventory(ctx, tx, inventoryID, skuID, sku.AvailableQuantity); err != nil { return err } @@ -381,7 +436,7 @@ WHERE id = $1 return ErrSKUNotFound } - if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := updateSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { return err } @@ -544,6 +599,42 @@ ORDER BY level ASC, sort_num ASC, id ASC return categories, nil } +// ListGroupNodes loads product group nodes. +func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { + rows, err := r.db.QueryContext(ctx, ` +SELECT id, + node_type, + name, + parent_id, + level, + image_json, + sort_num, + status +FROM product.product_category +WHERE node_type = 1 + AND ($1 = false OR status = 1) +ORDER BY sort_num ASC, id ASC +`, onlyVisible) + if err != nil { + return nil, fmt.Errorf("query group nodes: %w", err) + } + defer rows.Close() + + groups := make([]*CategoryRecord, 0) + for rows.Next() { + group, err := scanCategory(rows) + if err != nil { + return nil, err + } + groups = append(groups, group) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate group nodes: %w", err) + } + + return groups, nil +} + func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) { products, err := r.loadProductsByIDs(ctx, []string{productID}) if err != nil { @@ -746,7 +837,11 @@ RETURNING id, if err != nil { return nil, err } - inventory, err := upsertSKUInventory(ctx, tx, createdSKUID, sku.AvailableQuantity) + inventoryID, err := inventoryIDFromSKU(sku) + if err != nil { + return nil, err + } + inventory, err := upsertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.AvailableQuantity) if err != nil { return nil, err } @@ -759,15 +854,22 @@ RETURNING id, return createdSKU, nil } -func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) (*InventoryRecord, error) { +func inventoryIDFromSKU(sku SKURecord) (int64, error) { + if sku.Inventory == nil { + return 0, errors.New("inventory id is required") + } + return parseID(sku.Inventory.ID, "inventory id") +} + +func upsertSKUInventory(ctx context.Context, tx *sql.Tx, inventoryID, 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) +VALUES ($1, $2, $3) 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) +`, inventoryID, skuID, availableQuantity) inventory, err := scanInventory(row) if err != nil { return nil, fmt.Errorf("upsert sku inventory %s: %w", formatID(skuID), err) @@ -775,6 +877,24 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create return inventory, nil } +func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) (*InventoryRecord, error) { + row := tx.QueryRowContext(ctx, ` +UPDATE product.product_item_inventory +SET available_quantity = $2, + updated_at = NOW() +WHERE sku_id = $1 +RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at +`, skuID, availableQuantity) + inventory, err := scanInventory(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), ErrSKUNotFound) + } + if err != nil { + return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), err) + } + return inventory, nil +} + func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID, categoryID string) error { parsedBindingID, err := parseID(bindingID, "category binding id") if err != nil { @@ -800,6 +920,55 @@ ON CONFLICT (product_id, category_id) DO NOTHING return nil } +func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord) (*CategoryRecord, error) { + id, err := parseID(category.ID, "category id") + if err != nil { + return nil, err + } + + parentID := sql.NullInt64{} + if strings.TrimSpace(category.ParentID) != "" { + parsedParentID, err := parseID(category.ParentID, "parent_id") + if err != nil { + return nil, err + } + parentID = sql.NullInt64{Int64: parsedParentID, Valid: true} + } + + imageJSON, err := normalizeCategoryImageJSON(category.ImageJSON) + if err != nil { + return nil, err + } + + row := tx.QueryRowContext(ctx, ` +INSERT INTO product.product_category ( + id, + node_type, + name, + parent_id, + level, + image_json, + sort_num, + status +) +VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8) +RETURNING id, + node_type, + name, + parent_id, + level, + image_json, + sort_num, + status +`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), imageJSON, category.SortNum, int16(category.Status)) + + createdCategory, err := scanCategory(row) + if err != nil { + return nil, fmt.Errorf("insert category node: %w", err) + } + return createdCategory, 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 { @@ -1195,6 +1364,17 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } +func normalizeCategoryImageJSON(raw string) ([]byte, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return []byte("[]"), nil + } + if !json.Valid([]byte(raw)) { + return nil, fmt.Errorf("invalid image_json") + } + return []byte(raw), nil +} + func productCrossBorderJSON(product ProductRecord) ([]byte, error) { if strings.TrimSpace(product.CrossBorderJSON) != "" { attrs := []byte(product.CrossBorderJSON) diff --git a/internal/server/product_server.go b/internal/server/product_server.go index d5e73c7..b0756bd 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "math" "strconv" "strings" @@ -28,6 +29,12 @@ import ( const ( defaultPageSize = int32(20) maxPageSize = int32(100) + + categoryNodeType = int32(0) + groupNodeType = int32(1) + + defaultNodeStatus = int32(1) + maxNodeNameLength = 100 ) // ProductServer implements productv1.ProductServiceServer. @@ -72,6 +79,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create product.ID = s.idgen.NextString() for i := range skus { skus[i].ID = s.idgen.NextString() + skus[i].Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()} } if product.LeafCategoryID != "" { product.CategoryBindingID = s.idgen.NextString() @@ -220,6 +228,112 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis }, nil } +// CreateCategoryTree creates a top-level category and optional second-level categories. +func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.CreateCategoryTreeRequest) (*productv1.CreateCategoryTreeResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + + parent, children, err := categoryTreeFromCreateRequest(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + parent.ID = s.idgen.NextString() + for i := range children { + children[i].ID = s.idgen.NextString() + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_category_tree", trace.WithAttributes( + attribute.String("category.name", parent.Name), + attribute.Int("category.child_count", len(children)), + )) + defer dbSpan.End() + + createdParent, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, parent, children) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("create category tree failed", zap.String("category_name", parent.Name), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "create category tree: %v", err) + } + + category := toProtoCategoryNode(createdParent) + for _, child := range createdChildren { + category.Children = append(category.Children, toProtoCategoryNode(child)) + } + + return &productv1.CreateCategoryTreeResponse{ + Category: category, + }, nil +} + +// CreateGroup creates a top-level product group. +func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + + group, err := groupFromCreateRequest(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + group.ID = s.idgen.NextString() + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_group", trace.WithAttributes( + attribute.String("group.name", group.Name), + )) + defer dbSpan.End() + + createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("create group failed", zap.String("group_name", group.Name), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "create group: %v", err) + } + + return &productv1.CreateGroupResponse{ + Group: toProtoGroupNode(createdGroup), + }, nil +} + +// ListGroups returns product groups. +func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) { + onlyVisible := false + if req != nil { + onlyVisible = req.GetOnlyVisible() + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_groups", trace.WithAttributes( + attribute.Bool("group.only_visible", onlyVisible), + )) + defer dbSpan.End() + + groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("list groups failed", zap.Bool("only_visible", onlyVisible), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "list groups: %v", err) + } + dbSpan.SetAttributes(attribute.Int("group.result_count", len(groups))) + + protoGroups := make([]*productv1.GroupNode, 0, len(groups)) + for _, group := range groups { + protoGroups = append(protoGroups, toProtoGroupNode(group)) + } + + return &productv1.ListGroupsResponse{ + Groups: protoGroups, + }, nil +} + func totalPages(total int64, pageSize int32) int32 { if total <= 0 || pageSize <= 0 { return 0 @@ -231,6 +345,122 @@ func totalPages(total int64, pageSize int32) int32 { return int32(pages) } +func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (repository.CategoryRecord, []repository.CategoryRecord, error) { + name, err := normalizeNodeName(req.GetName(), "name") + if err != nil { + return repository.CategoryRecord{}, nil, err + } + imageJSON, err := normalizeNodeImageJSON(req.GetImageJson()) + if err != nil { + return repository.CategoryRecord{}, nil, err + } + statusValue, err := normalizeNodeStatus(req.Status) + if err != nil { + return repository.CategoryRecord{}, nil, err + } + + parent := repository.CategoryRecord{ + NodeType: categoryNodeType, + Name: name, + Level: 1, + ImageJSON: imageJSON, + SortNum: req.GetSortNum(), + Status: statusValue, + } + + children := make([]repository.CategoryRecord, 0, len(req.GetChildren())) + childNames := make(map[string]struct{}, len(req.GetChildren())) + for _, child := range req.GetChildren() { + if child == nil { + return repository.CategoryRecord{}, nil, errors.New("children item is required") + } + childName, err := normalizeNodeName(child.GetName(), "children.name") + if err != nil { + return repository.CategoryRecord{}, nil, err + } + if _, exists := childNames[childName]; exists { + return repository.CategoryRecord{}, nil, errors.New("children.name must be unique") + } + childNames[childName] = struct{}{} + + childImageJSON, err := normalizeNodeImageJSON(child.GetImageJson()) + if err != nil { + return repository.CategoryRecord{}, nil, err + } + childStatus, err := normalizeNodeStatus(child.Status) + if err != nil { + return repository.CategoryRecord{}, nil, err + } + + children = append(children, repository.CategoryRecord{ + NodeType: categoryNodeType, + Name: childName, + Level: 2, + ImageJSON: childImageJSON, + SortNum: child.GetSortNum(), + Status: childStatus, + }) + } + + return parent, children, nil +} + +func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, error) { + name, err := normalizeNodeName(req.GetName(), "name") + if err != nil { + return repository.CategoryRecord{}, err + } + imageJSON, err := normalizeNodeImageJSON(req.GetImageJson()) + if err != nil { + return repository.CategoryRecord{}, err + } + statusValue, err := normalizeNodeStatus(req.Status) + if err != nil { + return repository.CategoryRecord{}, err + } + + return repository.CategoryRecord{ + NodeType: groupNodeType, + Name: name, + Level: 1, + ImageJSON: imageJSON, + SortNum: req.GetSortNum(), + Status: statusValue, + }, nil +} + +func normalizeNodeName(raw, field string) (string, error) { + name := strings.TrimSpace(raw) + if name == "" { + return "", fmt.Errorf("%s is required", field) + } + if len([]rune(name)) > maxNodeNameLength { + return "", fmt.Errorf("%s length must be <= %d", field, maxNodeNameLength) + } + return name, nil +} + +func normalizeNodeImageJSON(raw string) (string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "[]", nil + } + if !json.Valid([]byte(raw)) { + return "", errors.New("image_json must be valid json") + } + return raw, nil +} + +func normalizeNodeStatus(statusValue *int32) (int32, error) { + if statusValue == nil { + return defaultNodeStatus, nil + } + if *statusValue != 0 && *statusValue != 1 { + return 0, errors.New("status must be 0 or 1") + } + return *statusValue, nil +} + func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) { spuNo := strings.TrimSpace(req.GetSpuNo()) if spuNo == "" { @@ -622,3 +852,19 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor Children: []*productv1.CategoryNode{}, } } + +func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode { + if group == nil { + return nil + } + return &productv1.GroupNode{ + GroupId: group.ID, + NodeType: group.NodeType, + Name: group.Name, + ParentId: group.ParentID, + Level: group.Level, + ImageJson: group.ImageJSON, + SortNum: group.SortNum, + Status: group.Status, + } +} diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 43a2173..6f0d721 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -201,6 +201,7 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( ); COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储可售库存、锁定库存和已售数量'; +COMMENT ON COLUMN product.product_item_inventory.id IS '库存记录主键,由商品服务应用层生成雪花 ID'; COMMENT ON COLUMN product.product_item_inventory.available_quantity IS 'SKU 当前可售库存'; COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存'; COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量';