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:
robinj0726 2026-07-13 18:44:30 +08:00
commit bbe9ee0be2
4 changed files with 461 additions and 32 deletions

View File

@ -30,7 +30,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 创建商品的完整字段、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 业务字段。服务会在入库前生成: 创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成:
@ -38,7 +38,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|---|---|---| |---|---|---|
| `product_id` | 服务内 Snowflake 生成 | `product.products.id` | | `product_id` | 服务内 Snowflake 生成 | `product.products.id` |
| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.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` | | 分类绑定 ID | 传入 `leaf_category_id` 时服务内 Snowflake 生成 | `product.product_category_bindings.id` |
常用请求字段: 常用请求字段:
@ -101,7 +101,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|---|---|---|---| |---|---|---|---|
| `product_id` | `string` | 是 | 商品 SPU ID | | `product_id` | `string` | 是 | 商品 SPU ID |
响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。 响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。时间字段统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
### `ListCategoryProducts` ### `ListCategoryProducts`
@ -121,6 +121,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| `total` | `int64` | 分类/分组下商品总数 | | `total` | `int64` | 分类/分组下商品总数 |
| `total_pages` | `int32` | 总页数 | | `total_pages` | `int32` | 总页数 |
`products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
### `ListCategoryTree` ### `ListCategoryTree`
| 字段 | 类型 | 必填 | 说明 | | 字段 | 类型 | 必填 | 说明 |

View File

@ -241,6 +241,57 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P
return createdProduct, createdSKUs, nil 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. // UpdateProduct updates mutable SPU fields.
func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error { func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error {
attrs, err := json.Marshal(product.Attrs) attrs, err := json.Marshal(product.Attrs)
@ -323,6 +374,10 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
if err != nil { if err != nil {
return err return err
} }
inventoryID, err := inventoryIDFromSKU(sku)
if err != nil {
return err
}
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
@ -339,7 +394,7 @@ RETURNING id
return fmt.Errorf("insert sku: %w", err) 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 return err
} }
@ -383,7 +438,7 @@ WHERE id = $1
return ErrSKUNotFound return ErrSKUNotFound
} }
if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { if _, err := updateSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil {
return err return err
} }
@ -546,6 +601,42 @@ ORDER BY level ASC, sort_num ASC, id ASC
return categories, nil 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) { func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) {
products, err := r.loadProductsByIDs(ctx, []string{productID}) products, err := r.loadProductsByIDs(ctx, []string{productID})
if err != nil { if err != nil {
@ -748,7 +839,11 @@ RETURNING id,
if err != nil { if err != nil {
return nil, err 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 { if err != nil {
return nil, err return nil, err
} }
@ -761,23 +856,43 @@ RETURNING id,
return createdSKU, nil 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, ` row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_item_inventory (id, sku_id, spu_no, sku_no, available_quantity) 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 FROM product.product_items pi
JOIN product.products p ON p.id = pi.product_id JOIN product.products p ON p.id = pi.product_id
WHERE pi.id = $1 WHERE pi.id = $2
ON CONFLICT (sku_id) DO UPDATE RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at
SET available_quantity = EXCLUDED.available_quantity, `, inventoryID, skuID, availableQuantity)
spu_no = EXCLUDED.spu_no, inventory, err := scanInventory(row)
sku_no = EXCLUDED.sku_no, 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() updated_at = NOW()
WHERE sku_id = $1
RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at
`, skuID, availableQuantity) `, skuID, availableQuantity)
inventory, err := scanInventory(row) 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 { 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 return inventory, nil
} }
@ -807,6 +922,55 @@ ON CONFLICT (product_id, category_id) DO NOTHING
return nil 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) { func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) {
result := make(map[string][]SKURecord, len(productIDs)) result := make(map[string][]SKURecord, len(productIDs))
if len(productIDs) == 0 { if len(productIDs) == 0 {
@ -1202,6 +1366,17 @@ func normalizeAttributesJSON(raw string) ([]byte, error) {
return []byte(raw), nil 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) { func productCrossBorderJSON(product ProductRecord) ([]byte, error) {
if strings.TrimSpace(product.CrossBorderJSON) != "" { if strings.TrimSpace(product.CrossBorderJSON) != "" {
attrs := []byte(product.CrossBorderJSON) attrs := []byte(product.CrossBorderJSON)

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"math" "math"
"strconv" "strconv"
"strings" "strings"
@ -28,6 +29,12 @@ import (
const ( const (
defaultPageSize = int32(20) defaultPageSize = int32(20)
maxPageSize = int32(100) maxPageSize = int32(100)
categoryNodeType = int32(0)
groupNodeType = int32(1)
defaultNodeStatus = int32(1)
maxNodeNameLength = 100
) )
// ProductServer implements productv1.ProductServiceServer. // ProductServer implements productv1.ProductServiceServer.
@ -72,6 +79,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
product.ID = s.idgen.NextString() product.ID = s.idgen.NextString()
for i := range skus { for i := range skus {
skus[i].ID = s.idgen.NextString() skus[i].ID = s.idgen.NextString()
skus[i].Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()}
} }
if product.LeafCategoryID != "" { if product.LeafCategoryID != "" {
product.CategoryBindingID = s.idgen.NextString() product.CategoryBindingID = s.idgen.NextString()
@ -220,6 +228,112 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis
}, nil }, 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 { func totalPages(total int64, pageSize int32) int32 {
if total <= 0 || pageSize <= 0 { if total <= 0 || pageSize <= 0 {
return 0 return 0
@ -231,6 +345,122 @@ func totalPages(total int64, pageSize int32) int32 {
return int32(pages) 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) { func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) {
spuNo := strings.TrimSpace(req.GetSpuNo()) spuNo := strings.TrimSpace(req.GetSpuNo())
if spuNo == "" { if spuNo == "" {
@ -450,6 +680,18 @@ func timestampToTime(value *timestamppb.Timestamp) *time.Time {
return &t 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 { func validatePositiveID(raw, field string) error {
if raw == "" { if raw == "" {
return errors.New(field + " is required") return errors.New(field + " is required")
@ -485,9 +727,9 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
V2: sku.V2, V2: sku.V2,
K3: sku.K3, K3: sku.K3,
V3: sku.V3, V3: sku.V3,
DeletedAt: timestampOrNil(sku.DeletedAt), DeletedAt: timePtrToMillisString(sku.DeletedAt),
CreatedAt: timestamppb.New(sku.CreatedAt), CreatedAt: timeToMillisString(sku.CreatedAt),
UpdatedAt: timestamppb.New(sku.UpdatedAt), UpdatedAt: timeToMillisString(sku.UpdatedAt),
Inventory: toProtoInventory(sku.Inventory), Inventory: toProtoInventory(sku.Inventory),
}) })
} }
@ -499,8 +741,8 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
SellingPoint: product.SellingPoint, SellingPoint: product.SellingPoint,
Status: product.Status, Status: product.Status,
Skus: protoSKUs, Skus: protoSKUs,
CreatedAt: timestamppb.New(product.CreatedAt), CreatedAt: timeToMillisString(product.CreatedAt),
UpdatedAt: timestamppb.New(product.UpdatedAt), UpdatedAt: timeToMillisString(product.UpdatedAt),
ImageIds: product.ImageIDs, ImageIds: product.ImageIDs,
BrandId: product.BrandID, BrandId: product.BrandID,
SupplierId: product.SupplierID, SupplierId: product.SupplierID,
@ -514,8 +756,8 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
FreightFixedAmount: product.FreightFixedAmount, FreightFixedAmount: product.FreightFixedAmount,
FreightTemplateId: product.FreightTemplateID, FreightTemplateId: product.FreightTemplateID,
SaleTimeType: product.SaleTimeType, SaleTimeType: product.SaleTimeType,
ScheduledSaleTime: timestampOrNil(product.ScheduledSaleTime), ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime),
DeletedAt: timestampOrNil(product.DeletedAt), DeletedAt: timePtrToMillisString(product.DeletedAt),
} }
} }
@ -532,8 +774,8 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []re
}) })
} }
return &productv1.CategoryProduct{ return &productv1.CategoryProduct{
UpdatedAt: timestamppb.New(product.UpdatedAt), UpdatedAt: timeToMillisString(product.UpdatedAt),
CreatedAt: timestamppb.New(product.CreatedAt), CreatedAt: timeToMillisString(product.CreatedAt),
Title: product.Title, Title: product.Title,
ProductId: product.ID, ProductId: product.ID,
SpuNo: product.SPUNo, SpuNo: product.SPUNo,
@ -553,18 +795,11 @@ func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductI
AvailableQuantity: inventory.AvailableQuantity, AvailableQuantity: inventory.AvailableQuantity,
LockedQuantity: inventory.LockedQuantity, LockedQuantity: inventory.LockedQuantity,
SoldQuantity: inventory.SoldQuantity, SoldQuantity: inventory.SoldQuantity,
CreatedAt: timestamppb.New(inventory.CreatedAt), CreatedAt: timeToMillisString(inventory.CreatedAt),
UpdatedAt: timestamppb.New(inventory.UpdatedAt), 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 { func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode {
nodes := make(map[string]*productv1.CategoryNode, len(categories)) nodes := make(map[string]*productv1.CategoryNode, len(categories))
records := make(map[string]*repository.CategoryRecord, len(categories)) records := make(map[string]*repository.CategoryRecord, len(categories))
@ -617,3 +852,19 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor
Children: []*productv1.CategoryNode{}, 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,
}
}

View File

@ -203,6 +203,7 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory (
); );
COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储可售库存、锁定库存和已售数量'; 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.spu_no IS '商品 SPU 编码冗余字段,用于库存查询和对账';
COMMENT ON COLUMN product.product_item_inventory.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账'; COMMENT ON COLUMN product.product_item_inventory.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账';
COMMENT ON COLUMN product.product_item_inventory.available_quantity IS 'SKU 当前可售库存'; COMMENT ON COLUMN product.product_item_inventory.available_quantity IS 'SKU 当前可售库存';