Merge remote-tracking branch 'origin/dev1' into phase1

# Conflicts:
#	internal/repository/product_repository.go
This commit is contained in:
robinj0726 2026-07-13 17:21:28 +08:00
commit 6a4f7ad5fe
13 changed files with 1333 additions and 147 deletions

View File

@ -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)

110
README.md
View File

@ -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,27 +24,76 @@ 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`
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `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` 字段:
当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `sku_id` | `string` | 是 | SKU ID,由调用方生成 |
| `name` | `string` | 是 | SKU 名称 |
| `price` | `int64` | 是 | 售价,单位:分 |
| `available_quantity` | `int32` | 是 | 初始可售库存 |
| `attributes_json` | `string` | 否 | 规格属性 JSON 字符串 |
创建商品时,调用方只提交商品业务字段和 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"
}
]
}
```
响应只返回创建结果摘要,字段结构如下:
```json
{
"data": {
"item_id": 726390485721088000,
"title": "澳洲和牛家庭装"
},
"success": true,
"code": 0,
"message": "success"
}
```
其中 `data.item_id` 是服务生成后的商品主键 ID,`data.title` 是商品标题。
### `GetProduct`
@ -71,6 +121,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[]` | 子分类列表 |
## 技术栈
| 项 | 选型 |
@ -129,6 +200,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;同一部署环境内不同服务实例必须使用不同值 |
### 可观测性
@ -138,7 +210,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` |
@ -162,8 +234,8 @@ grpcurl -plaintext localhost:50052 list
grpcurl -plaintext -d '{"product_id":"<snowflake-id>"}' \
localhost:50052 ids.product.v1.ProductService/GetProduct
# 创建商品
grpcurl -plaintext -d '{"product_id":"<snowflake-id>","spu_no":"<spu-no>","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \
# 创建商品;product_id 和 sku_id 由服务生成
grpcurl -plaintext -d '{"spu_no":"<spu-no>","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \
localhost:50052 ids.product.v1.ProductService/CreateProduct
# 分页查询分类商品

View File

@ -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"
@ -37,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()
@ -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()),

View File

@ -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:

View File

@ -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 查询补齐分类展示信息。
---

1
go.mod
View File

@ -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

2
go.sum
View File

@ -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=

View File

@ -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)
}

View File

@ -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")
}
}

View File

@ -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()

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,7 @@ import (
"math"
"strconv"
"strings"
"time"
"go.opentelemetry.io/otel/attribute"
otelcodes "go.opentelemetry.io/otel/codes"
@ -14,10 +15,12 @@ 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"
"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"
)
@ -32,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()
}
@ -46,6 +50,7 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, ob
}
return &ProductServer{
repo: repo,
idgen: idGenerator,
logger: logger,
observer: observer,
}
@ -61,24 +66,51 @@ 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()
}
if product.LeafCategoryID != "" {
product.CategoryBindingID = s.idgen.NextString()
}
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()
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())
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))
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()
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
}
@ -147,9 +179,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{
@ -161,6 +193,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
@ -173,11 +232,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")
@ -192,19 +246,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())
}
@ -214,20 +302,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")
}
@ -235,21 +314,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")
@ -271,21 +471,149 @@ 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,
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),
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,
CrossBorderInfo: toProtoCrossBorderInfo(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))
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,
NodeType: category.NodeType,
Name: category.Name,
ParentId: category.ParentID,
Level: category.Level,
ImageJson: category.ImageJSON,
SortNum: category.SortNum,
Status: category.Status,
Children: []*productv1.CategoryNode{},
}
}

View File

@ -159,6 +159,7 @@ CREATE TABLE IF NOT EXISTS product.product_items (
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 +170,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 乐观锁版本号';