mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
Merge remote-tracking branch 'origin/dev1' into phase1
# Conflicts: # internal/repository/product_repository.go # scripts/sql/recreate-product-tables.sql
This commit is contained in:
commit
bbe9ee0be2
@ -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` |
|
||||
|
||||
常用请求字段:
|
||||
@ -101,7 +101,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
|---|---|---|---|
|
||||
| `product_id` | `string` | 是 | 商品 SPU ID |
|
||||
|
||||
响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。
|
||||
响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。时间字段统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
|
||||
|
||||
### `ListCategoryProducts`
|
||||
|
||||
@ -121,6 +121,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
||||
| `total` | `int64` | 分类/分组下商品总数 |
|
||||
| `total_pages` | `int32` | 总页数 |
|
||||
|
||||
`products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
|
||||
|
||||
### `ListCategoryTree`
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|
||||
@ -241,6 +241,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)
|
||||
@ -323,6 +374,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 {
|
||||
@ -339,7 +394,7 @@ RETURNING id
|
||||
return fmt.Errorf("insert sku: %w", err)
|
||||
}
|
||||
|
||||
if _, err := upsertSKUInventory(ctx, tx, skuID, sku.AvailableQuantity); err != nil {
|
||||
if _, err := insertSKUInventory(ctx, tx, inventoryID, skuID, sku.AvailableQuantity); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -383,7 +438,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
|
||||
}
|
||||
|
||||
@ -546,6 +601,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 {
|
||||
@ -748,7 +839,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 := insertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.AvailableQuantity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -761,23 +856,43 @@ 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 insertSKUInventory(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, spu_no, sku_no, available_quantity)
|
||||
SELECT pi.id, pi.id, p.spu_no, pi.sku_no, $2
|
||||
SELECT $1, pi.id, p.spu_no, pi.sku_no, $3
|
||||
FROM product.product_items pi
|
||||
JOIN product.products p ON p.id = pi.product_id
|
||||
WHERE pi.id = $1
|
||||
ON CONFLICT (sku_id) DO UPDATE
|
||||
SET available_quantity = EXCLUDED.available_quantity,
|
||||
spu_no = EXCLUDED.spu_no,
|
||||
sku_no = EXCLUDED.sku_no,
|
||||
WHERE pi.id = $2
|
||||
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at
|
||||
`, inventoryID, skuID, availableQuantity)
|
||||
inventory, err := scanInventory(row)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("insert sku inventory %s: %w", formatID(skuID), err)
|
||||
}
|
||||
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("upsert sku inventory %s: %w", formatID(skuID), err)
|
||||
return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), err)
|
||||
}
|
||||
return inventory, nil
|
||||
}
|
||||
@ -807,6 +922,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 {
|
||||
@ -1202,6 +1366,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)
|
||||
|
||||
@ -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 == "" {
|
||||
@ -450,6 +680,18 @@ func timestampToTime(value *timestamppb.Timestamp) *time.Time {
|
||||
return &t
|
||||
}
|
||||
|
||||
func timeToMillisString(value time.Time) string {
|
||||
return strconv.FormatInt(value.UnixMilli(), 10)
|
||||
}
|
||||
|
||||
func timePtrToMillisString(value *time.Time) *string {
|
||||
millis := ""
|
||||
if value != nil {
|
||||
millis = timeToMillisString(*value)
|
||||
}
|
||||
return &millis
|
||||
}
|
||||
|
||||
func validatePositiveID(raw, field string) error {
|
||||
if raw == "" {
|
||||
return errors.New(field + " is required")
|
||||
@ -485,9 +727,9 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
V2: sku.V2,
|
||||
K3: sku.K3,
|
||||
V3: sku.V3,
|
||||
DeletedAt: timestampOrNil(sku.DeletedAt),
|
||||
CreatedAt: timestamppb.New(sku.CreatedAt),
|
||||
UpdatedAt: timestamppb.New(sku.UpdatedAt),
|
||||
DeletedAt: timePtrToMillisString(sku.DeletedAt),
|
||||
CreatedAt: timeToMillisString(sku.CreatedAt),
|
||||
UpdatedAt: timeToMillisString(sku.UpdatedAt),
|
||||
Inventory: toProtoInventory(sku.Inventory),
|
||||
})
|
||||
}
|
||||
@ -499,8 +741,8 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
SellingPoint: product.SellingPoint,
|
||||
Status: product.Status,
|
||||
Skus: protoSKUs,
|
||||
CreatedAt: timestamppb.New(product.CreatedAt),
|
||||
UpdatedAt: timestamppb.New(product.UpdatedAt),
|
||||
CreatedAt: timeToMillisString(product.CreatedAt),
|
||||
UpdatedAt: timeToMillisString(product.UpdatedAt),
|
||||
ImageIds: product.ImageIDs,
|
||||
BrandId: product.BrandID,
|
||||
SupplierId: product.SupplierID,
|
||||
@ -514,8 +756,8 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
|
||||
FreightFixedAmount: product.FreightFixedAmount,
|
||||
FreightTemplateId: product.FreightTemplateID,
|
||||
SaleTimeType: product.SaleTimeType,
|
||||
ScheduledSaleTime: timestampOrNil(product.ScheduledSaleTime),
|
||||
DeletedAt: timestampOrNil(product.DeletedAt),
|
||||
ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime),
|
||||
DeletedAt: timePtrToMillisString(product.DeletedAt),
|
||||
}
|
||||
}
|
||||
|
||||
@ -532,8 +774,8 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []re
|
||||
})
|
||||
}
|
||||
return &productv1.CategoryProduct{
|
||||
UpdatedAt: timestamppb.New(product.UpdatedAt),
|
||||
CreatedAt: timestamppb.New(product.CreatedAt),
|
||||
UpdatedAt: timeToMillisString(product.UpdatedAt),
|
||||
CreatedAt: timeToMillisString(product.CreatedAt),
|
||||
Title: product.Title,
|
||||
ProductId: product.ID,
|
||||
SpuNo: product.SPUNo,
|
||||
@ -553,18 +795,11 @@ func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductI
|
||||
AvailableQuantity: inventory.AvailableQuantity,
|
||||
LockedQuantity: inventory.LockedQuantity,
|
||||
SoldQuantity: inventory.SoldQuantity,
|
||||
CreatedAt: timestamppb.New(inventory.CreatedAt),
|
||||
UpdatedAt: timestamppb.New(inventory.UpdatedAt),
|
||||
CreatedAt: timeToMillisString(inventory.CreatedAt),
|
||||
UpdatedAt: timeToMillisString(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))
|
||||
@ -617,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,
|
||||
}
|
||||
}
|
||||
|
||||
@ -203,6 +203,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.spu_no IS '商品 SPU 编码冗余字段,用于库存查询和对账';
|
||||
COMMENT ON COLUMN product.product_item_inventory.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账';
|
||||
COMMENT ON COLUMN product.product_item_inventory.available_quantity IS 'SKU 当前可售库存';
|
||||
|
||||
Loading…
Reference in New Issue
Block a user