From f50ef1a9128c9e4c43b3582807d507baca904ce6 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Sat, 4 Jul 2026 08:15:25 +0800 Subject: [PATCH 01/44] Add .DS_Store to .gitignore to prevent unnecessary file tracking --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 7ed088c..3d87d50 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .env /bin/ *.exe +.DS_Store From f7bb383877e84b63922d86898936fe346c5d77a6 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Sun, 5 Jul 2026 13:23:42 +0800 Subject: [PATCH 02/44] Update database schema references from `product_schema` to `product` across documentation and codebase, ensuring consistency in environment configurations, repository access, and architectural constraints. Enhance clarity in README and development documents regarding database usage and constraints. --- AGENTS.md | 6 +- README.md | 22 ++-- docker-compose.yaml | 2 +- docs/ARCHITECTURE.md | 22 ++-- docs/DEVELOPMENT.md | 12 +- go.sum | 2 - internal/config/config.go | 16 +-- internal/repository/product_repository.go | 153 +++++++++++++++------- 8 files changed, 143 insertions(+), 92 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fe10a16..99ae049 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ - 本服务 Go Module 名: `llms.idsbuybuybuy.com/ecommerce/ids-svc-product` - 外部依赖契约: `llms.idsbuybuybuy.com/ecommerce/ids-proto`(已通过 `go.mod` 中的本地 `replace` 关联到 `../ids-proto`) -- 数据库命名空间: PostgreSQL 的 `product_schema` +- 数据库命名空间: PostgreSQL 的 `product` - Proto 契约路径: `ids-proto/proto/ids/product/v1/product.proto`(包名 `ids.product.v1`,Go 包 `productv1`) # Task 1: 依赖对齐与本地拦截 (`go.mod`) @@ -29,7 +29,7 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto ```env SERVER_PORT=:50052 -POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema +POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product NATS_URL=nats://localhost:4222 ``` @@ -45,7 +45,7 @@ NATS_URL=nats://localhost:4222 ## 3.1 `internal/repository/product_repository.go` -- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product_schema.products`(SPU)和 `product_schema.skus` 的底座 CRUD +- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.skus` 的底座 CRUD - 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属的 SKU 列表 - 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用 - **【红线 ARC-001】**:严禁在这里编写任何跨 Schema 的 JOIN 查询 diff --git a/README.md b/README.md index a085d2b..653a82b 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格 |---|---| | 语言 | Go 1.26 | | RPC | gRPC (`google.golang.org/grpc`) | -| 数据库 | PostgreSQL `product_schema`(`github.com/jackc/pgx/v5`) | +| 数据库 | PostgreSQL `product`(`github.com/jackc/pgx/v5`) | | 配置 | 环境变量 + 可选本地 `.env`(`github.com/joho/godotenv`) | | 契约 | `llms.idsbuybuybuy.com/ecommerce/ids-proto`(本地 `replace ../ids-proto`) | @@ -30,7 +30,7 @@ ids-svc-product/ ├── cmd/main.go # 服务入口 ├── internal/ │ ├── config/config.go # 配置加载 -│ ├── repository/product_repository.go # product_schema 数据访问 +│ ├── repository/product_repository.go # product 数据访问 │ └── server/product_server.go # gRPC 契约实现 ├── docs/ │ ├── ARCHITECTURE.md # 架构白皮书 @@ -64,7 +64,7 @@ cp .env.example .env | `POSTGRES_USER` | `postgres` | 数据库用户 | | `POSTGRES_PASSWORD` | `postgres` | 数据库密码 | | `POSTGRES_DB` | `ids_ecommerce` | 数据库名 | -| `POSTGRES_SCHEMA` | `product_schema` | 搜索路径 | +| `POSTGRES_SCHEMA` | `product` | 搜索路径 | | `POSTGRES_SSLMODE` | `disable` | SSL 模式 | | `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址(首版查询链路不依赖) | @@ -85,25 +85,25 @@ go run ./cmd grpcurl -plaintext localhost:50052 list # 查询单个商品 -grpcurl -plaintext -d '{"product_id":""}' \ +grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct # 批量查询 -grpcurl -plaintext -d '{"product_ids":["",""]}' \ +grpcurl -plaintext -d '{"product_ids":["",""]}' \ localhost:50052 ids.product.v1.ProductService/BatchGetProducts ``` ## 数据模型 -商品域采用 SPU/SKU 分层,**仅读写** `product_schema`: +商品域采用 SPU/SKU 分层,**仅读写** `product`: | 表 | 职责 | |---|---| -| `product_schema.products` | SPU 主表(名称、描述、状态、扩展属性) | -| `product_schema.skus` | SKU 明细(规格、价格、库存) | +| `product.products` | SPU 主表(名称、描述、状态、扩展属性) | +| `product.skus` | SKU 明细(规格、价格、库存) | - 价格字段统一为 `BIGINT` / Go `int64`,单位:**分** -- 禁止跨 Schema JOIN(`order_schema`、`user_schema` 等) +- 禁止跨 Schema JOIN(`trade`、`customer` 等) ## 架构约束 @@ -116,7 +116,7 @@ grpcurl -plaintext -d '{"product_ids":["",""]}' \ | ID | 约束 | |---|---| -| ARC-PROD-001 | 仅读写 `product_schema`,禁止跨 Schema JOIN | +| ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN | | ARC-PROD-003 | `BatchGetProducts` 对重复 ID 去重,缺失 ID 静默跳过 | | ARC-PROD-004 | 价格字段统一 `int64`(分) | | ARC-PROD-005 | 状态枚举强对齐 `productv1.ProductStatus` | @@ -127,7 +127,7 @@ grpcurl -plaintext -d '{"product_ids":["",""]}' \ ids-svc-order (算价) ──BatchGetProducts──▶ ids-svc-product │ ▼ - PG product_schema + PG product ``` 订单服务通过 gRPC 批量拉取 SKU 价格,**不得**跨库查询商品表。 diff --git a/docker-compose.yaml b/docker-compose.yaml index 64cbd7e..a0ccfd0 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -13,7 +13,7 @@ services: POSTGRES_USER: ${POSTGRES_USER:-postgres} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres123} POSTGRES_DB: ${POSTGRES_DB:-ids_ecommerce} - POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product_schema} + POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product} POSTGRES_SSLMODE: ${POSTGRES_SSLMODE:-disable} NATS_URL: nats://nats:4222 GOMODCACHE: /go/pkg/mod diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3f9d6c0..c835136 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -12,9 +12,9 @@ ### 1.1 数据隔离红线 [ARC-PROD-001] -- 本服务**仅允许**读写 PostgreSQL 中的 `product_schema`。 -- 绝对禁止跨 Schema 去 `JOIN` `order_schema`、`user_schema` 或任何其他业务 Schema 的表。 -- 任何关于订单状态、用户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。 +- 本服务**仅允许**读写 PostgreSQL 中的 `product`。 +- 绝对禁止跨 Schema 去 `JOIN` `trade`、`customer` 或任何其他业务 Schema 的表。 +- 任何关于订单状态、客户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。 ### 1.2 数据模型 (PostgreSQL) @@ -22,8 +22,8 @@ | 表 | 职责 | |---|---| -| `product_schema.products` | SPU 主表,保存商品级公共信息、上下架状态与基础描述。 | -| `product_schema.skus` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 | +| `product.products` | SPU 主表,保存商品级公共信息、上下架状态与基础描述。 | +| `product.skus` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 | 所有价格字段(如 `price`)统一采用 `BIGINT` / Go `int64`,单位为**分**。禁止使用 `float32`、`float64` 或数据库浮点类型表达金额。 @@ -49,7 +49,7 @@ │ ▼ ┌──────────────────────────────┐ - │ PG product_schema │ + │ PG product │ └──────────────────────────────┘ ``` @@ -59,7 +59,7 @@ |---|---|---| | 启动信宿 | `cmd/main.go` | 服务启动信宿,负责加载配置、初始化 PostgreSQL 连接池、创建 repository,并拉起 gRPC 监听端口。 | | 契约实现层 | `internal/server/` | 实现 `ids-proto` 生成的 `ProductServiceServer` 接口。**禁止**在此处编写任何 SQL;主要职责是解析入参、调用 repository、映射 `productv1.Product` 与 `productv1.SKU` 强类型响应。 | -| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product_schema.products` 与 `product_schema.skus` 的 CRUD 和批量查询能力。 | +| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product.products` 与 `product.skus` 的 CRUD 和批量查询能力。 | | 配置底座 | `internal/config/` | 轻量读取环境变量,优先加载本地 `.env`,生产环境无 `.env` 时静默降级到环境注入。 | --- @@ -77,7 +77,7 @@ ### 3.2 查询实现约束 -1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product_schema.products` 与 `product_schema.skus` 之间做本域关联或分步查询,但不得访问其他 Schema。 +1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.skus` 之间做本域关联或分步查询,但不得访问其他 Schema。 2. **[ARC-PROD-003] 批量查询必须稳定去重:** `BatchGetProducts` 应对重复 `product_id` 输入做安全处理,避免无意义 DB 放大,并保持返回结果语义清晰。 3. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 4. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 @@ -91,7 +91,7 @@ | 环境变量 | 默认值 | 说明 | |---|---|---| | `SERVER_PORT` | `:50052` | gRPC Server 监听地址。 | -| `POSTGRES_DSN` | `postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema` | PostgreSQL 连接字符串,必须包含 `product_schema` 搜索路径或由 SQL 显式限定 Schema。 | +| `POSTGRES_DSN` | `postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product` | PostgreSQL 连接字符串,必须包含 `product` 搜索路径或由 SQL 显式限定 Schema。 | | `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址;当前商品查询主链路不依赖 NATS。 | ### 4.1 `.env` 加载策略 [ARC-PROD-006] @@ -124,7 +124,7 @@ 3. 数据库操作必须收敛在 `internal/repository` 层,**严禁**在 `internal/server` 抛出 naked SQL。 4. 严格按照 `ids-proto` 中 `ids.product.v1` / `productv1` 的结构体定义进行序列化与反序列化。 5. 商品状态枚举必须强对齐 `productv1.ProductStatus`,不得在 gRPC 响应中暴露内部字符串状态。 -6. 跨域数据(订单、用户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。 +6. 跨域数据(订单、客户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。 7. `BatchGetProducts` 是订单算价链路的关键接口,应优先保证低延迟、批量查询与清晰错误语义。 --- @@ -133,7 +133,7 @@ | ID | 约束 | |---|---| -| ARC-PROD-001 | 仅读写 `product_schema`,禁止跨 Schema JOIN | +| ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN | | ARC-PROD-002 | SPU/SKU 只允许在商品域 Schema 内关联 | | ARC-PROD-003 | `BatchGetProducts` 必须对重复输入做稳定处理 | | ARC-PROD-004 | 价格字段统一 `int64`,单位为分 | diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index fe1feae..8902826 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -20,7 +20,7 @@ |---|---| | Go Module | `llms.idsbuybuybuy.com/ecommerce/ids-svc-product` | | 外部依赖契约 | `llms.idsbuybuybuy.com/ecommerce/ids-proto`(通过 `go.mod` 中 `replace` 关联到 `../ids-proto`) | -| 数据库命名空间 | PostgreSQL `product_schema` | +| 数据库命名空间 | PostgreSQL `product` | | Go 工具链 | **Go 1.26** | | Proto 契约路径 | `ids-proto/proto/ids/product/v1/product.proto` | | Proto 包名 | `ids.product.v1` | @@ -59,7 +59,7 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto ```env SERVER_PORT=:50052 -POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema +POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product NATS_URL=nats://localhost:4222 ``` @@ -111,13 +111,13 @@ ids-svc-product/ ### 3.1 `internal/repository/product_repository.go` -- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product_schema.products`(SPU)和 `product_schema.skus` 的底座 CRUD。 +- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.skus` 的底座 CRUD。 - 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属 SKU 列表。 - 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用。 - `BatchGetProducts` 必须对重复 `product_id` 输入做稳定去重,避免 DB 查询放大。 - 单商品不存在时应返回明确 not found 语义,便于 gRPC 层映射为 `codes.NotFound`。 - **【红线 ARC-PROD-001】**:严禁编写任何跨 Schema 的 JOIN 查询。 -- **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `product_schema` 内关联或分步查询。 +- **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `product` 内关联或分步查询。 --- @@ -164,7 +164,7 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository |---|---| | 1 | 价格字段一律 `int64`(单位:分),**禁止** `float64` | | 2 | 状态枚举强对齐 `productv1.ProductStatus` | -| 3 | repository 仅操作 `product_schema.products` 与 `product_schema.skus` | +| 3 | repository 仅操作 `product.products` 与 `product.skus` | | 4 | 禁止跨 Schema JOIN(**[ARC-PROD-001]**) | | 5 | `BatchGetProducts` 必须支持批量查询与重复输入去重(**[ARC-PROD-003]**) | | 6 | DB / gRPC 等底座错误须有完整日志包装(`log` 或 `slog`) | @@ -190,7 +190,7 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository | 开发任务 | 架构约束 | |---|---| -| `repository` 仅操作 `product_schema` | [ARC-PROD-001] | +| `repository` 仅操作 `product` | [ARC-PROD-001] | | SPU/SKU 只在商品域内关联 | [ARC-PROD-002] | | 批量商品查询去重与稳定返回 | [ARC-PROD-003] | | 价格字段统一 `int64` 分单位 | [ARC-PROD-004] | diff --git a/go.sum b/go.sum index 2012369..d350e61 100644 --- a/go.sum +++ b/go.sum @@ -11,8 +11,6 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= diff --git a/internal/config/config.go b/internal/config/config.go index 967ca66..4da757c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -10,14 +10,14 @@ import ( ) const ( - defaultServerPort = ":50052" - defaultPostgresHost = "localhost" - defaultPostgresPort = "5432" - defaultPostgresUser = "postgres" - defaultPostgresPass = "postgres" - defaultPostgresDB = "ids_ecommerce" - defaultPostgresSchema = "product_schema" - defaultNATSURL = "nats://localhost:4222" + defaultServerPort = ":50052" + defaultPostgresHost = "localhost" + defaultPostgresPort = "5432" + defaultPostgresUser = "postgres" + defaultPostgresPass = "postgres" + defaultPostgresDB = "ids_ecommerce" + defaultPostgresSchema = "product" + defaultNATSURL = "nats://localhost:4222" ) // Config holds runtime configuration loaded from environment variables. diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 0105019..beae8c4 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "strconv" "strings" "time" @@ -18,7 +19,7 @@ var ErrProductNotFound = errors.New("product not found") // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") -// ProductRecord is the persistence model for product_schema.products (SPU). +// ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { ID string SPUCode string @@ -30,19 +31,19 @@ type ProductRecord struct { UpdatedAt time.Time } -// SKURecord is the persistence model for product_schema.skus. +// SKURecord is the persistence model for product.skus. type SKURecord struct { - ID string - ProductID string - Name string - Price int64 - Stock int32 - AttributesJSONB string - CreatedAt time.Time - UpdatedAt time.Time + ID string + ProductID string + Name string + Price int64 + Stock int32 + AttributesJSONB string + CreatedAt time.Time + UpdatedAt time.Time } -// ProductRepository provides CRUD access to product_schema tables only [ARC-PROD-001]. +// ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. type ProductRepository struct { db *sql.DB } @@ -52,17 +53,12 @@ func NewProductRepository(db *sql.DB) *ProductRepository { return &ProductRepository{db: db} } -// EnsureSchema adds product-domain columns and the skus table when missing. +// EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` -ALTER TABLE product_schema.products - ADD COLUMN IF NOT EXISTS description TEXT NOT NULL DEFAULT ''; -ALTER TABLE product_schema.products - ADD COLUMN IF NOT EXISTS status VARCHAR(32) NOT NULL DEFAULT 'draft'; - -CREATE TABLE IF NOT EXISTS product_schema.skus ( - id UUID PRIMARY KEY, - product_id UUID NOT NULL REFERENCES product_schema.products(id) ON DELETE CASCADE, +CREATE TABLE IF NOT EXISTS product.skus ( + id BIGINT PRIMARY KEY, + product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, name VARCHAR(256) NOT NULL, price BIGINT NOT NULL CHECK (price >= 0), stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0), @@ -70,10 +66,10 @@ CREATE TABLE IF NOT EXISTS product_schema.skus ( created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -CREATE INDEX IF NOT EXISTS idx_skus_product_id ON product_schema.skus(product_id); +CREATE INDEX IF NOT EXISTS idx_skus_product_id ON product.skus(product_id); ` if _, err := r.db.ExecContext(ctx, ddl); err != nil { - return fmt.Errorf("ensure product_schema tables: %w", err) + return fmt.Errorf("ensure product tables: %w", err) } return nil } @@ -88,10 +84,15 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe attrs = []byte("{}") } + id, err := parseID(product.ID, "product id") + if err != nil { + return err + } + _, err = r.db.ExecContext(ctx, ` -INSERT INTO product_schema.products (id, spu_code, title, description, status, attrs) +INSERT INTO product.products (id, spu_no, title, sell_point, status, cross_border) VALUES ($1, $2, $3, $4, $5, $6::jsonb) -`, product.ID, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) +`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) if err != nil { return fmt.Errorf("insert product %s: %w", product.ID, err) } @@ -108,11 +109,16 @@ func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRe attrs = []byte("{}") } + id, err := parseID(product.ID, "product id") + if err != nil { + return err + } + res, err := r.db.ExecContext(ctx, ` -UPDATE product_schema.products -SET spu_code = $2, title = $3, description = $4, status = $5, attrs = $6::jsonb, updated_at = NOW() +UPDATE product.products +SET spu_no = $2, title = $3, sell_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW() WHERE id = $1 -`, product.ID, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) +`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) if err != nil { return fmt.Errorf("update product %s: %w", product.ID, err) } @@ -129,7 +135,11 @@ WHERE id = $1 // DeleteProduct removes an SPU and its SKUs via ON DELETE CASCADE. func (r *ProductRepository) DeleteProduct(ctx context.Context, productID string) error { - res, err := r.db.ExecContext(ctx, `DELETE FROM product_schema.products WHERE id = $1`, productID) + id, err := parseID(productID, "product id") + if err != nil { + return err + } + res, err := r.db.ExecContext(ctx, `DELETE FROM product.products WHERE id = $1`, id) if err != nil { return fmt.Errorf("delete product %s: %w", productID, err) } @@ -151,10 +161,19 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error return err } + id, err := parseID(sku.ID, "sku id") + if err != nil { + return err + } + productID, err := parseID(sku.ProductID, "product id") + if err != nil { + return err + } + _, err = r.db.ExecContext(ctx, ` -INSERT INTO product_schema.skus (id, product_id, name, price, stock, attributes) +INSERT INTO product.skus (id, product_id, name, price, stock, attributes) VALUES ($1, $2, $3, $4, $5, $6::jsonb) -`, sku.ID, sku.ProductID, sku.Name, sku.Price, sku.Stock, attrs) +`, id, productID, sku.Name, sku.Price, sku.Stock, attrs) if err != nil { return fmt.Errorf("insert sku %s: %w", sku.ID, err) } @@ -168,11 +187,15 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error return err } + id, err := parseID(sku.ID, "sku id") + if err != nil { + return err + } res, err := r.db.ExecContext(ctx, ` -UPDATE product_schema.skus +UPDATE product.skus SET name = $2, price = $3, stock = $4, attributes = $5::jsonb, updated_at = NOW() WHERE id = $1 -`, sku.ID, sku.Name, sku.Price, sku.Stock, attrs) +`, id, sku.Name, sku.Price, sku.Stock, attrs) if err != nil { return fmt.Errorf("update sku %s: %w", sku.ID, err) } @@ -189,7 +212,11 @@ WHERE id = $1 // DeleteSKU removes a SKU row. func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error { - res, err := r.db.ExecContext(ctx, `DELETE FROM product_schema.skus WHERE id = $1`, skuID) + id, err := parseID(skuID, "sku id") + if err != nil { + return err + } + res, err := r.db.ExecContext(ctx, `DELETE FROM product.skus WHERE id = $1`, id) if err != nil { return fmt.Errorf("delete sku %s: %w", skuID, err) } @@ -262,13 +289,17 @@ func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs [] placeholders := make([]string, len(productIDs)) args := make([]any, len(productIDs)) for i, id := range productIDs { + parsed, err := parseID(id, "product id") + if err != nil { + return nil, err + } placeholders[i] = fmt.Sprintf("$%d", i+1) - args[i] = id + args[i] = parsed } query := fmt.Sprintf(` -SELECT id, spu_code, title, description, status, attrs, created_at, updated_at -FROM product_schema.products +SELECT id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +FROM product.products WHERE id IN (%s) ORDER BY created_at ASC `, strings.Join(placeholders, ", ")) @@ -303,13 +334,17 @@ func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs placeholders := make([]string, len(productIDs)) args := make([]any, len(productIDs)) for i, id := range productIDs { + parsed, err := parseID(id, "product id") + if err != nil { + return nil, err + } placeholders[i] = fmt.Sprintf("$%d", i+1) - args[i] = id + args[i] = parsed } query := fmt.Sprintf(` SELECT id, product_id, name, price, stock, attributes, created_at, updated_at -FROM product_schema.skus +FROM product.skus WHERE product_id IN (%s) ORDER BY created_at ASC `, strings.Join(placeholders, ", ")) @@ -341,15 +376,17 @@ type rowScanner interface { func scanProduct(scanner rowScanner) (*ProductRecord, error) { var ( rec ProductRecord - status string + id int64 + status int16 attrsJSON []byte ) if err := scanner.Scan( - &rec.ID, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &id, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, ); err != nil { return nil, fmt.Errorf("scan product: %w", err) } + rec.ID = formatID(id) rec.Status = statusFromDB(status) if len(attrsJSON) > 0 { if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil { @@ -362,14 +399,18 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { func scanSKU(scanner rowScanner) (*SKURecord, error) { var ( rec SKURecord + id int64 + productID int64 attrsJSON []byte ) if err := scanner.Scan( - &rec.ID, &rec.ProductID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &id, &productID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, ); err != nil { return nil, fmt.Errorf("scan sku: %w", err) } + rec.ID = formatID(id) + rec.ProductID = formatID(productID) rec.AttributesJSONB = string(attrsJSON) if rec.AttributesJSONB == "" { rec.AttributesJSONB = "{}" @@ -403,28 +444,40 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } -func statusToDB(status productv1.ProductStatus) string { +func statusToDB(status productv1.ProductStatus) int16 { switch status { case productv1.ProductStatus_PRODUCT_STATUS_DRAFT: - return "draft" + return 0 case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE: - return "on_sale" + return 1 case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE: - return "off_sale" + return 3 default: - return "unspecified" + return 0 } } -func statusFromDB(status string) productv1.ProductStatus { +func statusFromDB(status int16) productv1.ProductStatus { switch status { - case "draft": + case 0: return productv1.ProductStatus_PRODUCT_STATUS_DRAFT - case "on_sale": + case 1: return productv1.ProductStatus_PRODUCT_STATUS_ON_SALE - case "off_sale": + case 3: return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE default: return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED } } + +func parseID(raw, field string) (int64, error) { + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return 0, fmt.Errorf("%s must be a positive snowflake id", field) + } + return id, nil +} + +func formatID(id int64) string { + return strconv.FormatInt(id, 10) +} From 2ef7742b6a48ef92a886d737d7e09e872cfdaf86 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 11:58:27 +0800 Subject: [PATCH 03/44] Implement CreateProduct and ListCategoryProducts functionalities in the product server, enhancing product management capabilities. Update README with new RPC methods and examples. Refactor product repository to support SKU insertion and category-based product listing, ensuring efficient data handling and retrieval. --- README.md | 10 ++ internal/repository/product_repository.go | 151 ++++++++++++++++++ internal/server/product_server.go | 178 ++++++++++++++++++++++ 3 files changed, 339 insertions(+) diff --git a/README.md b/README.md index 653a82b..fbc43da 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,9 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格 | RPC | 说明 | 主要调用方 | |-----|------|-----------| +| `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 / 订单服务 | +| `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | | `BatchGetProducts` | 批量拉取商品快照,减少算价阶段 N 次 RPC | `ids-svc-order` | 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 @@ -88,9 +90,17 @@ grpcurl -plaintext localhost:50052 list grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct +# 创建商品 +grpcurl -plaintext -d '{"product":{"product_id":"","spu_code":"","name":"商品名称","description":"商品描述","status":"PRODUCT_STATUS_DRAFT","skus":[]}}' \ + localhost:50052 ids.product.v1.ProductService/CreateProduct + # 批量查询 grpcurl -plaintext -d '{"product_ids":["",""]}' \ localhost:50052 ids.product.v1.ProductService/BatchGetProducts + +# 分页查询分类商品 +grpcurl -plaintext -d '{"category_id":"","page":1,"page_size":20}' \ + localhost:50052 ids.product.v1.ProductService/ListCategoryProducts ``` ## 数据模型 diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index beae8c4..e64acb1 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -99,6 +99,48 @@ VALUES ($1, $2, $3, $4, $5, $6::jsonb) return nil } +// CreateProductWithSKUs inserts an SPU and its optional SKU list in one transaction. +func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product ProductRecord, skus []SKURecord) (*ProductRecord, []SKURecord, error) { + attrs, err := json.Marshal(product.Attrs) + if err != nil { + return nil, nil, fmt.Errorf("marshal product attrs: %w", err) + } + if product.Attrs == nil { + attrs = []byte("{}") + } + + id, err := parseID(product.ID, "product id") + if err != nil { + return nil, nil, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, nil, fmt.Errorf("begin create product: %w", err) + } + defer tx.Rollback() + + createdProduct, err := insertProduct(ctx, tx, id, product, attrs) + if err != nil { + return nil, nil, err + } + + createdSKUs := make([]SKURecord, 0, len(skus)) + for _, sku := range skus { + createdSKU, err := insertSKU(ctx, tx, product.ID, sku) + if err != nil { + return nil, nil, err + } + createdSKUs = append(createdSKUs, *createdSKU) + } + + if err := tx.Commit(); err != nil { + return nil, nil, fmt.Errorf("commit create product: %w", err) + } + + return createdProduct, createdSKUs, nil +} + // UpdateProduct updates mutable SPU fields. func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error { attrs, err := json.Marshal(product.Attrs) @@ -274,6 +316,73 @@ func (r *ProductRepository) BatchGetProducts(ctx context.Context, productIDs []s return products, skuMap, nil } +// ListCategoryProducts loads a paginated product list for a category ID. +func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*ProductRecord, map[string][]SKURecord, int64, error) { + parsedCategoryID, err := parseID(categoryID, "category id") + if err != nil { + return nil, nil, 0, err + } + + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + + var total int64 + if err := r.db.QueryRowContext(ctx, ` +SELECT COUNT(*) +FROM product.products +WHERE category_ids @> ARRAY[$1]::BIGINT[] +`, parsedCategoryID).Scan(&total); err != nil { + return nil, nil, 0, fmt.Errorf("count category products: %w", err) + } + if total == 0 { + return []*ProductRecord{}, map[string][]SKURecord{}, 0, nil + } + + offset := int64(page-1) * int64(pageSize) + rows, err := r.db.QueryContext(ctx, ` +SELECT id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +FROM product.products +WHERE category_ids @> ARRAY[$1]::BIGINT[] +ORDER BY created_at DESC, id DESC +LIMIT $2 OFFSET $3 +`, parsedCategoryID, pageSize, offset) + if err != nil { + return nil, nil, 0, fmt.Errorf("query category products: %w", err) + } + defer rows.Close() + + products := make([]*ProductRecord, 0, pageSize) + for rows.Next() { + product, err := scanProduct(rows) + if err != nil { + return nil, nil, 0, err + } + products = append(products, product) + } + if err := rows.Err(); err != nil { + return nil, nil, 0, fmt.Errorf("iterate category products: %w", err) + } + if len(products) == 0 { + return products, map[string][]SKURecord{}, total, nil + } + + foundIDs := make([]string, 0, len(products)) + for _, product := range products { + foundIDs = append(foundIDs, product.ID) + } + + skuMap, err := r.loadSKUsByProductIDs(ctx, foundIDs) + if err != nil { + return nil, nil, 0, err + } + + return products, skuMap, total, nil +} + func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) { products, err := r.loadProductsByIDs(ctx, []string{productID}) if err != nil { @@ -325,6 +434,48 @@ ORDER BY created_at ASC return products, nil } +func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRecord, attrs []byte) (*ProductRecord, error) { + row := tx.QueryRowContext(ctx, ` +INSERT INTO product.products (id, spu_no, title, sell_point, status, cross_border) +VALUES ($1, $2, $3, $4, $5, $6::jsonb) +RETURNING id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) + + createdProduct, err := scanProduct(row) + if err != nil { + return nil, fmt.Errorf("insert product %s: %w", product.ID, err) + } + return createdProduct, nil +} + +func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) { + attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) + if err != nil { + return nil, err + } + + id, err := parseID(sku.ID, "sku id") + if err != nil { + return nil, err + } + parsedProductID, err := parseID(productID, "product id") + if err != nil { + return nil, err + } + + row := tx.QueryRowContext(ctx, ` +INSERT INTO product.skus (id, product_id, name, price, stock, attributes) +VALUES ($1, $2, $3, $4, $5, $6::jsonb) +RETURNING id, product_id, name, price, stock, attributes, created_at, updated_at +`, id, parsedProductID, sku.Name, sku.Price, sku.Stock, attrs) + + createdSKU, err := scanSKU(row) + if err != nil { + return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) + } + return createdSKU, 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 { diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 603dff2..3b22756 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -2,7 +2,11 @@ package server import ( "context" + "encoding/json" "errors" + "math" + "strconv" + "strings" "go.uber.org/zap" "google.golang.org/grpc/codes" @@ -14,6 +18,11 @@ import ( "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" ) +const ( + defaultPageSize = int32(20) + maxPageSize = int32(100) +) + // ProductServer implements productv1.ProductServiceServer. type ProductServer struct { productv1.UnimplementedProductServiceServer @@ -33,6 +42,28 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger) *P } } +// CreateProduct creates a product SPU and optional SKU list. +func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) { + if req == nil || req.GetProduct() == nil { + return nil, status.Error(codes.InvalidArgument, "product is required") + } + + product, skus, err := productFromProto(req.GetProduct()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + createdProduct, createdSKUs, err := s.repo.CreateProductWithSKUs(ctx, product, skus) + if err != nil { + s.logger.Error("create product failed", zap.String("product_id", product.ID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "create product: %v", err) + } + + return &productv1.CreateProductResponse{ + Product: toProtoProduct(createdProduct, createdSKUs), + }, nil +} + // GetProduct returns a single SPU and its SKU list. func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProductRequest) (*productv1.GetProductResponse, error) { if req == nil || req.GetProductId() == "" { @@ -75,6 +106,152 @@ func (s *ProductServer) BatchGetProducts(ctx context.Context, req *productv1.Bat }, nil } +// ListCategoryProducts returns a paginated product list under a category. +func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { + if req == nil || req.GetCategoryId() == "" { + return nil, status.Error(codes.InvalidArgument, "category_id is required") + } + categoryID, err := strconv.ParseInt(req.GetCategoryId(), 10, 64) + if err != nil || categoryID <= 0 { + return nil, status.Error(codes.InvalidArgument, "category_id must be a positive snowflake id") + } + + page := req.GetPage() + if page <= 0 { + page = 1 + } + pageSize := req.GetPageSize() + if pageSize <= 0 { + pageSize = defaultPageSize + } + if pageSize > maxPageSize { + pageSize = maxPageSize + } + + products, skuMap, total, err := s.repo.ListCategoryProducts(ctx, req.GetCategoryId(), page, pageSize) + if err != nil { + s.logger.Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "list category products: %v", err) + } + + protoProducts := make([]*productv1.Product, 0, len(products)) + for _, product := range products { + protoProducts = append(protoProducts, toProtoProduct(product, skuMap[product.ID])) + } + + return &productv1.ListCategoryProductsResponse{ + Products: protoProducts, + Page: page, + PageSize: pageSize, + Total: total, + TotalPages: totalPages(total, pageSize), + }, nil +} + +func totalPages(total int64, pageSize int32) int32 { + if total <= 0 || pageSize <= 0 { + return 0 + } + pages := (total + int64(pageSize) - 1) / int64(pageSize) + if pages > math.MaxInt32 { + return math.MaxInt32 + } + return int32(pages) +} + +func productFromProto(product *productv1.Product) (repository.ProductRecord, []repository.SKURecord, error) { + productID := strings.TrimSpace(product.GetProductId()) + if err := validatePositiveID(productID, "product_id"); err != nil { + return repository.ProductRecord{}, nil, err + } + + spuCode := strings.TrimSpace(product.GetSpuCode()) + if spuCode == "" { + return repository.ProductRecord{}, nil, errors.New("spu_code is required") + } + + name := strings.TrimSpace(product.GetName()) + if name == "" { + return repository.ProductRecord{}, nil, errors.New("name is required") + } + + statusValue := product.GetStatus() + if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { + statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT + } + + record := repository.ProductRecord{ + ID: productID, + SPUCode: spuCode, + Name: name, + Description: product.GetDescription(), + Status: statusValue, + Attrs: map[string]any{}, + } + + skus := make([]repository.SKURecord, 0, len(product.GetSkus())) + for i, protoSKU := range product.GetSkus() { + sku, err := skuFromProto(productID, protoSKU) + if err != nil { + return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) + } + skus = append(skus, sku) + } + + return record, skus, nil +} + +func skuFromProto(productID string, sku *productv1.SKU) (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 + } + + if sku.GetProductId() != "" && sku.GetProductId() != productID { + return repository.SKURecord{}, errors.New("product_id must match product.product_id") + } + + 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") + } + if sku.GetStock() < 0 { + return repository.SKURecord{}, errors.New("stock must be greater than or equal to 0") + } + + attrs := strings.TrimSpace(sku.GetAttributesJsonb()) + if attrs != "" && !json.Valid([]byte(attrs)) { + return repository.SKURecord{}, errors.New("attributes_jsonb must be valid json") + } + + return repository.SKURecord{ + ID: skuID, + ProductID: productID, + Name: name, + Price: sku.GetPrice(), + Stock: sku.GetStock(), + AttributesJSONB: attrs, + }, nil +} + +func validatePositiveID(raw, field string) error { + if raw == "" { + return errors.New(field + " is required") + } + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return errors.New(field + " must be a positive snowflake id") + } + return nil +} + func toProtoProduct(product *repository.ProductRecord, skus []repository.SKURecord) *productv1.Product { if product == nil { return nil @@ -94,6 +271,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco return &productv1.Product{ ProductId: product.ID, + SpuCode: product.SPUCode, Name: product.Name, Description: product.Description, Status: product.Status, From 54bbf73f5636a35d62491a21ede8594b73d24326 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 12:44:58 +0800 Subject: [PATCH 04/44] Update references from `product.skus` to `product.product_items` in documentation and codebase, ensuring consistency in CRUD operations and architectural constraints. Enhance clarity in repository and development documents regarding data handling and schema relationships. --- AGENTS.md | 2 +- README.md | 2 +- docs/ARCHITECTURE.md | 6 +-- docs/DEVELOPMENT.md | 4 +- internal/repository/product_repository.go | 63 +++++++++++++++++------ 5 files changed, 53 insertions(+), 24 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 99ae049..38a7234 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,7 +45,7 @@ NATS_URL=nats://localhost:4222 ## 3.1 `internal/repository/product_repository.go` -- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.skus` 的底座 CRUD +- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.product_items` 的底座 CRUD - 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属的 SKU 列表 - 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用 - **【红线 ARC-001】**:严禁在这里编写任何跨 Schema 的 JOIN 查询 diff --git a/README.md b/README.md index fbc43da..d1ad241 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ grpcurl -plaintext -d '{"category_id":"","page":1,"page_s | 表 | 职责 | |---|---| | `product.products` | SPU 主表(名称、描述、状态、扩展属性) | -| `product.skus` | SKU 明细(规格、价格、库存) | +| `product.product_items` | SKU 明细(规格、价格、库存) | - 价格字段统一为 `BIGINT` / Go `int64`,单位:**分** - 禁止跨 Schema JOIN(`trade`、`customer` 等) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c835136..c5cf1df 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -23,7 +23,7 @@ | 表 | 职责 | |---|---| | `product.products` | SPU 主表,保存商品级公共信息、上下架状态与基础描述。 | -| `product.skus` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 | +| `product.product_items` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 | 所有价格字段(如 `price`)统一采用 `BIGINT` / Go `int64`,单位为**分**。禁止使用 `float32`、`float64` 或数据库浮点类型表达金额。 @@ -59,7 +59,7 @@ |---|---|---| | 启动信宿 | `cmd/main.go` | 服务启动信宿,负责加载配置、初始化 PostgreSQL 连接池、创建 repository,并拉起 gRPC 监听端口。 | | 契约实现层 | `internal/server/` | 实现 `ids-proto` 生成的 `ProductServiceServer` 接口。**禁止**在此处编写任何 SQL;主要职责是解析入参、调用 repository、映射 `productv1.Product` 与 `productv1.SKU` 强类型响应。 | -| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product.products` 与 `product.skus` 的 CRUD 和批量查询能力。 | +| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product.products` 与 `product.product_items` 的 CRUD 和批量查询能力。 | | 配置底座 | `internal/config/` | 轻量读取环境变量,优先加载本地 `.env`,生产环境无 `.env` 时静默降级到环境注入。 | --- @@ -77,7 +77,7 @@ ### 3.2 查询实现约束 -1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.skus` 之间做本域关联或分步查询,但不得访问其他 Schema。 +1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。 2. **[ARC-PROD-003] 批量查询必须稳定去重:** `BatchGetProducts` 应对重复 `product_id` 输入做安全处理,避免无意义 DB 放大,并保持返回结果语义清晰。 3. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 4. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 8902826..0baaee3 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -111,7 +111,7 @@ ids-svc-product/ ### 3.1 `internal/repository/product_repository.go` -- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.skus` 的底座 CRUD。 +- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.product_items` 的底座 CRUD。 - 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属 SKU 列表。 - 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用。 - `BatchGetProducts` 必须对重复 `product_id` 输入做稳定去重,避免 DB 查询放大。 @@ -164,7 +164,7 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository |---|---| | 1 | 价格字段一律 `int64`(单位:分),**禁止** `float64` | | 2 | 状态枚举强对齐 `productv1.ProductStatus` | -| 3 | repository 仅操作 `product.products` 与 `product.skus` | +| 3 | repository 仅操作 `product.products` 与 `product.product_items` | | 4 | 禁止跨 Schema JOIN(**[ARC-PROD-001]**) | | 5 | `BatchGetProducts` 必须支持批量查询与重复输入去重(**[ARC-PROD-003]**) | | 6 | DB / gRPC 等底座错误须有完整日志包装(`log` 或 `slog`) | diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index e64acb1..b81521c 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -31,7 +31,7 @@ type ProductRecord struct { UpdatedAt time.Time } -// SKURecord is the persistence model for product.skus. +// SKURecord is the persistence model for product.product_items. type SKURecord struct { ID string ProductID string @@ -56,17 +56,26 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` -CREATE TABLE IF NOT EXISTS product.skus ( +CREATE TABLE IF NOT EXISTS product.product_items ( id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, + sku_no VARCHAR(100) UNIQUE, name VARCHAR(256) NOT NULL, price BIGINT NOT NULL CHECK (price >= 0), stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0), attributes JSONB NOT NULL DEFAULT '{}', + version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), + deleted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -CREATE INDEX IF NOT EXISTS idx_skus_product_id ON product.skus(product_id); +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS sku_no VARCHAR(100), + ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; +CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL; ` if _, err := r.db.ExecContext(ctx, ddl); err != nil { return fmt.Errorf("ensure product tables: %w", err) @@ -90,7 +99,7 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe } _, err = r.db.ExecContext(ctx, ` -INSERT INTO product.products (id, spu_no, title, sell_point, status, cross_border) +INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) VALUES ($1, $2, $3, $4, $5, $6::jsonb) `, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) if err != nil { @@ -158,7 +167,7 @@ func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRe res, err := r.db.ExecContext(ctx, ` UPDATE product.products -SET spu_no = $2, title = $3, sell_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW() +SET spu_no = $2, title = $3, selling_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW() WHERE id = $1 `, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) if err != nil { @@ -175,13 +184,17 @@ WHERE id = $1 return nil } -// DeleteProduct removes an SPU and its SKUs via ON DELETE CASCADE. +// DeleteProduct soft-deletes an SPU and its SKUs. func (r *ProductRepository) DeleteProduct(ctx context.Context, productID string) error { id, err := parseID(productID, "product id") if err != nil { return err } - res, err := r.db.ExecContext(ctx, `DELETE FROM product.products WHERE id = $1`, id) + res, err := r.db.ExecContext(ctx, ` +UPDATE product.products +SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW() +WHERE id = $1 AND deleted_at IS NULL +`, id) if err != nil { return fmt.Errorf("delete product %s: %w", productID, err) } @@ -193,6 +206,14 @@ func (r *ProductRepository) DeleteProduct(ctx context.Context, productID string) if affected == 0 { return ErrProductNotFound } + + if _, err := r.db.ExecContext(ctx, ` +UPDATE product.product_items +SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW() +WHERE product_id = $1 AND deleted_at IS NULL +`, id); err != nil { + return fmt.Errorf("delete product skus %s: %w", productID, err) + } return nil } @@ -213,7 +234,7 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error } _, err = r.db.ExecContext(ctx, ` -INSERT INTO product.skus (id, product_id, name, price, stock, attributes) +INSERT INTO product.product_items (id, product_id, name, price, stock, attributes) VALUES ($1, $2, $3, $4, $5, $6::jsonb) `, id, productID, sku.Name, sku.Price, sku.Stock, attrs) if err != nil { @@ -234,7 +255,7 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error return err } res, err := r.db.ExecContext(ctx, ` -UPDATE product.skus +UPDATE product.product_items SET name = $2, price = $3, stock = $4, attributes = $5::jsonb, updated_at = NOW() WHERE id = $1 `, id, sku.Name, sku.Price, sku.Stock, attrs) @@ -252,13 +273,17 @@ WHERE id = $1 return nil } -// DeleteSKU removes a SKU row. +// DeleteSKU soft-deletes a SKU row. func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error { id, err := parseID(skuID, "sku id") if err != nil { return err } - res, err := r.db.ExecContext(ctx, `DELETE FROM product.skus WHERE id = $1`, id) + res, err := r.db.ExecContext(ctx, ` +UPDATE product.product_items +SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW() +WHERE id = $1 AND deleted_at IS NULL +`, id) if err != nil { return fmt.Errorf("delete sku %s: %w", skuID, err) } @@ -335,6 +360,7 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID SELECT COUNT(*) FROM product.products WHERE category_ids @> ARRAY[$1]::BIGINT[] + AND deleted_at IS NULL `, parsedCategoryID).Scan(&total); err != nil { return nil, nil, 0, fmt.Errorf("count category products: %w", err) } @@ -344,9 +370,10 @@ WHERE category_ids @> ARRAY[$1]::BIGINT[] offset := int64(page-1) * int64(pageSize) rows, err := r.db.QueryContext(ctx, ` -SELECT id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +SELECT id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at FROM product.products WHERE category_ids @> ARRAY[$1]::BIGINT[] + AND deleted_at IS NULL ORDER BY created_at DESC, id DESC LIMIT $2 OFFSET $3 `, parsedCategoryID, pageSize, offset) @@ -407,9 +434,10 @@ func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs [] } query := fmt.Sprintf(` -SELECT id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +SELECT id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at FROM product.products WHERE id IN (%s) + AND deleted_at IS NULL ORDER BY created_at ASC `, strings.Join(placeholders, ", ")) @@ -436,9 +464,9 @@ ORDER BY created_at ASC func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRecord, attrs []byte) (*ProductRecord, error) { row := tx.QueryRowContext(ctx, ` -INSERT INTO product.products (id, spu_no, title, sell_point, status, cross_border) +INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) VALUES ($1, $2, $3, $4, $5, $6::jsonb) -RETURNING id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at +RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at `, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) createdProduct, err := scanProduct(row) @@ -464,7 +492,7 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.skus (id, product_id, name, price, stock, attributes) +INSERT INTO product.product_items (id, product_id, name, price, stock, attributes) VALUES ($1, $2, $3, $4, $5, $6::jsonb) RETURNING id, product_id, name, price, stock, attributes, created_at, updated_at `, id, parsedProductID, sku.Name, sku.Price, sku.Stock, attrs) @@ -495,8 +523,9 @@ func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs query := fmt.Sprintf(` SELECT id, product_id, name, price, stock, attributes, created_at, updated_at -FROM product.skus +FROM product.product_items WHERE product_id IN (%s) + AND deleted_at IS NULL ORDER BY created_at ASC `, strings.Join(placeholders, ", ")) From 62ec3c43c4753408898d4adcd2559c6d70408921 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 15:39:30 +0800 Subject: [PATCH 05/44] Refactor product model and update CreateProduct logic to use new fields. Enhance SKU handling with inventory management and update README for consistency in product attributes. --- README.md | 7 +- internal/repository/product_repository.go | 180 +++++++++++++++------- internal/server/product_server.go | 96 ++++++------ 3 files changed, 172 insertions(+), 111 deletions(-) diff --git a/README.md b/README.md index d1ad241..912f856 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct # 创建商品 -grpcurl -plaintext -d '{"product":{"product_id":"","spu_code":"","name":"商品名称","description":"商品描述","status":"PRODUCT_STATUS_DRAFT","skus":[]}}' \ +grpcurl -plaintext -d '{"product_id":"","spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ localhost:50052 ids.product.v1.ProductService/CreateProduct # 批量查询 @@ -109,8 +109,9 @@ grpcurl -plaintext -d '{"category_id":"","page":1,"page_s | 表 | 职责 | |---|---| -| `product.products` | SPU 主表(名称、描述、状态、扩展属性) | -| `product.product_items` | SKU 明细(规格、价格、库存) | +| `product.products` | SPU 主表(标题、卖点、状态、扩展属性) | +| `product.product_items` | SKU 明细(规格、价格、属性) | +| `product.product_item_inventory` | SKU 库存销量(可售、锁定、已售) | - 价格字段统一为 `BIGINT` / Go `int64`,单位:**分** - 禁止跨 Schema JOIN(`trade`、`customer` 等) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index b81521c..fc90059 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -21,26 +21,26 @@ var ErrSKUNotFound = errors.New("sku not found") // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { - ID string - SPUCode string - Name string - Description string - Status productv1.ProductStatus - Attrs map[string]any - CreatedAt time.Time - UpdatedAt time.Time + ID string + SPUNo string + Title string + SellingPoint string + Status productv1.ProductStatus + Attrs map[string]any + CreatedAt time.Time + UpdatedAt time.Time } // SKURecord is the persistence model for product.product_items. type SKURecord struct { - ID string - ProductID string - Name string - Price int64 - Stock int32 - AttributesJSONB string - CreatedAt time.Time - UpdatedAt time.Time + ID string + ProductID string + Name string + Price int64 + AvailableQuantity int32 + AttributesJSON string + CreatedAt time.Time + UpdatedAt time.Time } // ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. @@ -59,23 +59,30 @@ func (r *ProductRepository) EnsureSchema(ctx context.Context) error { CREATE TABLE IF NOT EXISTS product.product_items ( id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, - sku_no VARCHAR(100) UNIQUE, + sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, price BIGINT NOT NULL CHECK (price >= 0), - stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0), 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), deleted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -ALTER TABLE product.product_items - ADD COLUMN IF NOT EXISTS sku_no VARCHAR(100), - ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0, - ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; +CREATE TABLE IF NOT EXISTS product.product_item_inventory ( + id BIGINT PRIMARY KEY, + sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, + available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), + locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), + sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), + version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) +); CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; ` if _, err := r.db.ExecContext(ctx, ddl); err != nil { return fmt.Errorf("ensure product tables: %w", err) @@ -101,7 +108,7 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe _, err = r.db.ExecContext(ctx, ` INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) VALUES ($1, $2, $3, $4, $5, $6::jsonb) -`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) +`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) if err != nil { return fmt.Errorf("insert product %s: %w", product.ID, err) } @@ -169,7 +176,7 @@ func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRe UPDATE product.products SET spu_no = $2, title = $3, selling_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW() WHERE id = $1 -`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) +`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) if err != nil { return fmt.Errorf("update product %s: %w", product.ID, err) } @@ -219,7 +226,7 @@ WHERE product_id = $1 AND deleted_at IS NULL // CreateSKU inserts a SKU row under an existing SPU. func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error { - attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) + attrs, err := normalizeAttributesJSON(sku.AttributesJSON) if err != nil { return err } @@ -233,19 +240,33 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error return err } - _, err = r.db.ExecContext(ctx, ` -INSERT INTO product.product_items (id, product_id, name, price, stock, attributes) -VALUES ($1, $2, $3, $4, $5, $6::jsonb) -`, id, productID, sku.Name, sku.Price, sku.Stock, attrs) + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin create sku: %w", err) + } + defer tx.Rollback() + + _, err = tx.ExecContext(ctx, ` +INSERT INTO product.product_items (id, product_id, name, price, attributes) +VALUES ($1, $2, $3, $4, $5::jsonb) +`, id, productID, sku.Name, sku.Price, attrs) if err != nil { return fmt.Errorf("insert sku %s: %w", sku.ID, err) } + + if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + return err + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit create sku: %w", err) + } return nil } // UpdateSKU updates mutable SKU fields. func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error { - attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) + attrs, err := normalizeAttributesJSON(sku.AttributesJSON) if err != nil { return err } @@ -254,11 +275,17 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error if err != nil { return err } - res, err := r.db.ExecContext(ctx, ` + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin update sku: %w", err) + } + defer tx.Rollback() + + res, err := tx.ExecContext(ctx, ` UPDATE product.product_items -SET name = $2, price = $3, stock = $4, attributes = $5::jsonb, updated_at = NOW() +SET name = $2, price = $3, attributes = $4::jsonb, updated_at = NOW() WHERE id = $1 -`, id, sku.Name, sku.Price, sku.Stock, attrs) +`, id, sku.Name, sku.Price, attrs) if err != nil { return fmt.Errorf("update sku %s: %w", sku.ID, err) } @@ -270,6 +297,14 @@ WHERE id = $1 if affected == 0 { return ErrSKUNotFound } + + if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + return err + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit update sku: %w", err) + } return nil } @@ -358,9 +393,10 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID var total int64 if err := r.db.QueryRowContext(ctx, ` SELECT COUNT(*) -FROM product.products -WHERE category_ids @> ARRAY[$1]::BIGINT[] - AND deleted_at IS NULL +FROM product.products p +JOIN product.product_category_bindings b ON b.product_id = p.id +WHERE b.category_id = $1 + AND p.deleted_at IS NULL `, parsedCategoryID).Scan(&total); err != nil { return nil, nil, 0, fmt.Errorf("count category products: %w", err) } @@ -370,11 +406,12 @@ WHERE category_ids @> ARRAY[$1]::BIGINT[] offset := int64(page-1) * int64(pageSize) rows, err := r.db.QueryContext(ctx, ` -SELECT id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at -FROM product.products -WHERE category_ids @> ARRAY[$1]::BIGINT[] - AND deleted_at IS NULL -ORDER BY created_at DESC, id DESC +SELECT p.id, p.spu_no, p.title, COALESCE(p.selling_point, ''), p.status, p.cross_border, p.created_at, p.updated_at +FROM product.products p +JOIN product.product_category_bindings b ON b.product_id = p.id +WHERE b.category_id = $1 + AND p.deleted_at IS NULL +ORDER BY p.created_at DESC, p.id DESC LIMIT $2 OFFSET $3 `, parsedCategoryID, pageSize, offset) if err != nil { @@ -467,7 +504,7 @@ func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRec INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) VALUES ($1, $2, $3, $4, $5, $6::jsonb) RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at -`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs) +`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) createdProduct, err := scanProduct(row) if err != nil { @@ -477,7 +514,7 @@ RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, } func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) { - attrs, err := normalizeAttributesJSON(sku.AttributesJSONB) + attrs, err := normalizeAttributesJSON(sku.AttributesJSON) if err != nil { return nil, err } @@ -492,18 +529,37 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (id, product_id, name, price, stock, attributes) -VALUES ($1, $2, $3, $4, $5, $6::jsonb) -RETURNING id, product_id, name, price, stock, attributes, created_at, updated_at -`, id, parsedProductID, sku.Name, sku.Price, sku.Stock, attrs) +INSERT INTO product.product_items (id, product_id, name, price, attributes) +VALUES ($1, $2, $3, $4, $5::jsonb) +RETURNING id, product_id, name, price, 0, attributes, created_at, updated_at +`, id, parsedProductID, sku.Name, sku.Price, attrs) createdSKU, err := scanSKU(row) if err != nil { return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) } + + if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + return nil, err + } + createdSKU.AvailableQuantity = sku.AvailableQuantity return createdSKU, nil } +func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) error { + _, err := tx.ExecContext(ctx, ` +INSERT INTO product.product_item_inventory (id, sku_id, available_quantity) +VALUES ($1, $1, $2) +ON CONFLICT (sku_id) DO UPDATE +SET available_quantity = EXCLUDED.available_quantity, + updated_at = NOW() +`, skuID, availableQuantity) + if err != nil { + return fmt.Errorf("upsert sku inventory %s: %w", formatID(skuID), err) + } + return nil +} + func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) { result := make(map[string][]SKURecord, len(productIDs)) if len(productIDs) == 0 { @@ -522,11 +578,19 @@ func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs } query := fmt.Sprintf(` -SELECT id, product_id, name, price, stock, attributes, created_at, updated_at -FROM product.product_items -WHERE product_id IN (%s) - AND deleted_at IS NULL -ORDER BY created_at ASC +SELECT pi.id, + pi.product_id, + pi.name, + pi.price, + COALESCE(inv.available_quantity, 0), + pi.attributes, + pi.created_at, + pi.updated_at +FROM product.product_items pi +LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id +WHERE pi.product_id IN (%s) + AND pi.deleted_at IS NULL +ORDER BY pi.created_at ASC `, strings.Join(placeholders, ", ")) rows, err := r.db.QueryContext(ctx, query, args...) @@ -561,7 +625,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { attrsJSON []byte ) if err := scanner.Scan( - &id, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &id, &rec.SPUNo, &rec.Title, &rec.SellingPoint, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, ); err != nil { return nil, fmt.Errorf("scan product: %w", err) } @@ -584,16 +648,16 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { attrsJSON []byte ) if err := scanner.Scan( - &id, &productID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &id, &productID, &rec.Name, &rec.Price, &rec.AvailableQuantity, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, ); err != nil { return nil, fmt.Errorf("scan sku: %w", err) } rec.ID = formatID(id) rec.ProductID = formatID(productID) - rec.AttributesJSONB = string(attrsJSON) - if rec.AttributesJSONB == "" { - rec.AttributesJSONB = "{}" + rec.AttributesJSON = string(attrsJSON) + if rec.AttributesJSON == "" { + rec.AttributesJSON = "{}" } return &rec, nil } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3b22756..50c1e25 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -44,11 +44,11 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger) *P // CreateProduct creates a product SPU and optional SKU list. func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) { - if req == nil || req.GetProduct() == nil { - return nil, status.Error(codes.InvalidArgument, "product is required") + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") } - product, skus, err := productFromProto(req.GetProduct()) + product, skus, err := productFromCreateRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } @@ -159,39 +159,39 @@ func totalPages(total int64, pageSize int32) int32 { return int32(pages) } -func productFromProto(product *productv1.Product) (repository.ProductRecord, []repository.SKURecord, error) { - productID := strings.TrimSpace(product.GetProductId()) +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 } - spuCode := strings.TrimSpace(product.GetSpuCode()) - if spuCode == "" { - return repository.ProductRecord{}, nil, errors.New("spu_code is required") + spuNo := strings.TrimSpace(req.GetSpuNo()) + if spuNo == "" { + return repository.ProductRecord{}, nil, errors.New("spu_no is required") } - name := strings.TrimSpace(product.GetName()) - if name == "" { - return repository.ProductRecord{}, nil, errors.New("name is required") + title := strings.TrimSpace(req.GetTitle()) + if title == "" { + return repository.ProductRecord{}, nil, errors.New("title is required") } - statusValue := product.GetStatus() + statusValue := req.GetStatus() if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT } record := repository.ProductRecord{ - ID: productID, - SPUCode: spuCode, - Name: name, - Description: product.GetDescription(), - Status: statusValue, - Attrs: map[string]any{}, + ID: productID, + SPUNo: spuNo, + Title: title, + SellingPoint: req.GetSellingPoint(), + Status: statusValue, + Attrs: map[string]any{}, } - skus := make([]repository.SKURecord, 0, len(product.GetSkus())) - for i, protoSKU := range product.GetSkus() { - sku, err := skuFromProto(productID, protoSKU) + skus := make([]repository.SKURecord, 0, len(req.GetSkus())) + for i, protoSKU := range req.GetSkus() { + sku, err := skuFromCreateInput(productID, protoSKU) if err != nil { return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) } @@ -201,7 +201,7 @@ func productFromProto(product *productv1.Product) (repository.ProductRecord, []r return record, skus, nil } -func skuFromProto(productID string, sku *productv1.SKU) (repository.SKURecord, error) { +func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repository.SKURecord, error) { if sku == nil { return repository.SKURecord{}, errors.New("sku is required") } @@ -211,10 +211,6 @@ func skuFromProto(productID string, sku *productv1.SKU) (repository.SKURecord, e return repository.SKURecord{}, err } - if sku.GetProductId() != "" && sku.GetProductId() != productID { - return repository.SKURecord{}, errors.New("product_id must match product.product_id") - } - name := strings.TrimSpace(sku.GetName()) if name == "" { return repository.SKURecord{}, errors.New("name is required") @@ -222,22 +218,22 @@ func skuFromProto(productID string, sku *productv1.SKU) (repository.SKURecord, e if sku.GetPrice() < 0 { return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") } - if sku.GetStock() < 0 { - return repository.SKURecord{}, errors.New("stock must be greater than or equal to 0") + if sku.GetAvailableQuantity() < 0 { + return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0") } - attrs := strings.TrimSpace(sku.GetAttributesJsonb()) + attrs := strings.TrimSpace(sku.GetAttributesJson()) if attrs != "" && !json.Valid([]byte(attrs)) { - return repository.SKURecord{}, errors.New("attributes_jsonb must be valid json") + return repository.SKURecord{}, errors.New("attributes_json must be valid json") } return repository.SKURecord{ - ID: skuID, - ProductID: productID, - Name: name, - Price: sku.GetPrice(), - Stock: sku.GetStock(), - AttributesJSONB: attrs, + ID: skuID, + ProductID: productID, + Name: name, + Price: sku.GetPrice(), + AvailableQuantity: sku.GetAvailableQuantity(), + AttributesJSON: attrs, }, nil } @@ -260,23 +256,23 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco protoSKUs := make([]*productv1.SKU, 0, len(skus)) for _, sku := range skus { protoSKUs = append(protoSKUs, &productv1.SKU{ - SkuId: sku.ID, - ProductId: sku.ProductID, - Name: sku.Name, - Price: sku.Price, - Stock: sku.Stock, - AttributesJsonb: sku.AttributesJSONB, + SkuId: sku.ID, + ProductId: sku.ProductID, + Name: sku.Name, + Price: sku.Price, + AvailableQuantity: sku.AvailableQuantity, + AttributesJson: sku.AttributesJSON, }) } return &productv1.Product{ - ProductId: product.ID, - SpuCode: product.SPUCode, - Name: product.Name, - Description: product.Description, - 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), } } From ac7ca612a68076485e407cea25c8e1d20233b7b8 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 15:53:29 +0800 Subject: [PATCH 06/44] Refactor product service to implement CreateProduct and ListCategoryProducts methods. Remove BatchGetProducts functionality and update documentation for clarity on product management capabilities. --- AGENTS.md | 3 +- README.md | 21 ++--------- docs/ARCHITECTURE.md | 14 ++++---- docs/DEVELOPMENT.md | 16 ++++----- internal/repository/product_repository.go | 44 ----------------------- internal/server/product_server.go | 22 ------------ 6 files changed, 15 insertions(+), 105 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 38a7234..09996bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,13 +47,12 @@ NATS_URL=nats://localhost:4222 - 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.product_items` 的底座 CRUD - 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属的 SKU 列表 -- 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用 - **【红线 ARC-001】**:严禁在这里编写任何跨 Schema 的 JOIN 查询 ## 3.2 `internal/server/product_server.go`(gRPC Server) - 引入 `llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/product/v1`(别名为 `productv1`) -- 实现 `productv1.ProductServiceServer` 接口中的 `GetProduct` 和 `BatchGetProducts` 方法 +- 实现 `productv1.ProductServiceServer` 接口中的 `CreateProduct`、`GetProduct` 和 `ListCategoryProducts` 方法 - 职责:解析入参 → 调用 repository 获取数据 → 组装并映射为 `productv1.Product` 和 `productv1.SKU` 强类型结构体返回 - 所有价格字段(`price`)必须严格映射为 `int64`(单位:分) diff --git a/README.md b/README.md index 912f856..6c1d1e7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ids-svc-product -IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格读取,为 `ids-svc-order` 算价链路提供稳定的 gRPC 商品快照查询能力。 +IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类商品查询与价格读取。 **设计原则:** 轻、快、稳、灵 · Doc-First · Schema-per-Service @@ -9,9 +9,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格 | RPC | 说明 | 主要调用方 | |-----|------|-----------| | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | -| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 / 订单服务 | +| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | -| `BatchGetProducts` | 批量拉取商品快照,减少算价阶段 N 次 RPC | `ids-svc-order` | 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 @@ -94,10 +93,6 @@ grpcurl -plaintext -d '{"product_id":""}' \ grpcurl -plaintext -d '{"product_id":"","spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ localhost:50052 ids.product.v1.ProductService/CreateProduct -# 批量查询 -grpcurl -plaintext -d '{"product_ids":["",""]}' \ - localhost:50052 ids.product.v1.ProductService/BatchGetProducts - # 分页查询分类商品 grpcurl -plaintext -d '{"category_id":"","page":1,"page_size":20}' \ localhost:50052 ids.product.v1.ProductService/ListCategoryProducts @@ -128,21 +123,9 @@ grpcurl -plaintext -d '{"category_id":"","page":1,"page_s | ID | 约束 | |---|---| | ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN | -| ARC-PROD-003 | `BatchGetProducts` 对重复 ID 去重,缺失 ID 静默跳过 | | ARC-PROD-004 | 价格字段统一 `int64`(分) | | ARC-PROD-005 | 状态枚举强对齐 `productv1.ProductStatus` | -## 与订单域协作 - -``` -ids-svc-order (算价) ──BatchGetProducts──▶ ids-svc-product - │ - ▼ - PG product -``` - -订单服务通过 gRPC 批量拉取 SKU 价格,**不得**跨库查询商品表。 - ## 相关仓库 | 仓库 | 关系 | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c5cf1df..3d02c81 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -66,21 +66,21 @@ ## 3. 商品查询契约 [ADR-PROD-001] -商品服务是订单服务提单算价时的商品事实来源。`ids-svc-order` 不允许跨 Schema 查询商品表,而必须通过本服务 gRPC 接口获取商品与 SKU 快照。 +商品服务是商品 SPU/SKU 主数据与分类商品查询的事实来源。其他服务不允许跨 Schema 查询商品表。 ### 3.1 核心 RPC | RPC | 调用方 | 语义 | |---|---|---| -| `GetProduct` | BFF / 后台 / 订单服务 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 | -| `BatchGetProducts` | `ids-svc-order` | 根据多个 `product_id` 批量返回商品及 SKU 列表,减少局域网算价阶段的 N 次调用。 | +| `CreateProduct` | 后台 / 运营系统 | 创建商品 SPU 及可选 SKU 列表。 | +| `GetProduct` | BFF / 后台 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 | +| `ListCategoryProducts` | BFF / 商城前台 | 根据分类/分组节点分页返回商品列表。 | ### 3.2 查询实现约束 1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。 -2. **[ARC-PROD-003] 批量查询必须稳定去重:** `BatchGetProducts` 应对重复 `product_id` 输入做安全处理,避免无意义 DB 放大,并保持返回结果语义清晰。 -3. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 -4. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 +2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 +3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 --- @@ -125,7 +125,6 @@ 4. 严格按照 `ids-proto` 中 `ids.product.v1` / `productv1` 的结构体定义进行序列化与反序列化。 5. 商品状态枚举必须强对齐 `productv1.ProductStatus`,不得在 gRPC 响应中暴露内部字符串状态。 6. 跨域数据(订单、客户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。 -7. `BatchGetProducts` 是订单算价链路的关键接口,应优先保证低延迟、批量查询与清晰错误语义。 --- @@ -135,7 +134,6 @@ |---|---| | ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN | | ARC-PROD-002 | SPU/SKU 只允许在商品域 Schema 内关联 | -| ARC-PROD-003 | `BatchGetProducts` 必须对重复输入做稳定处理 | | ARC-PROD-004 | 价格字段统一 `int64`,单位为分 | | ARC-PROD-005 | 状态枚举强对齐 `productv1` proto 枚举 | | ARC-PROD-006 | 配置加载优先 `.env`,生产无 `.env` 时静默降级 | diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 0baaee3..40446af 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -113,8 +113,6 @@ ids-svc-product/ - 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.product_items` 的底座 CRUD。 - 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属 SKU 列表。 -- 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用。 -- `BatchGetProducts` 必须对重复 `product_id` 输入做稳定去重,避免 DB 查询放大。 - 单商品不存在时应返回明确 not found 语义,便于 gRPC 层映射为 `codes.NotFound`。 - **【红线 ARC-PROD-001】**:严禁编写任何跨 Schema 的 JOIN 查询。 - **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `product` 内关联或分步查询。 @@ -124,7 +122,7 @@ ids-svc-product/ ### 3.2 `internal/server/product_server.go`(gRPC Server) - 引入 `llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/product/v1`(别名为 `productv1`)。 -- 实现 `productv1.ProductServiceServer` 接口中的 `GetProduct` 和 `BatchGetProducts` 方法。 +- 实现 `productv1.ProductServiceServer` 接口中的 `CreateProduct`、`GetProduct` 和 `ListCategoryProducts` 方法。 - 职责链: 1. 解析入参; 2. 校验必要字段; @@ -166,11 +164,10 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository | 2 | 状态枚举强对齐 `productv1.ProductStatus` | | 3 | repository 仅操作 `product.products` 与 `product.product_items` | | 4 | 禁止跨 Schema JOIN(**[ARC-PROD-001]**) | -| 5 | `BatchGetProducts` 必须支持批量查询与重复输入去重(**[ARC-PROD-003]**) | -| 6 | DB / gRPC 等底座错误须有完整日志包装(`log` 或 `slog`) | -| 7 | 序列化/反序列化严格对齐 `ids-proto` 中的 `productv1` | -| 8 | 配置加载优先 `godotenv.Load()`,生产环境无 `.env` 时须静默降级 | -| 9 | `internal/server` 禁止 SQL;`internal/repository` 禁止 proto 响应拼装 | +| 5 | DB / gRPC 等底座错误须有完整日志包装(`log` 或 `slog`) | +| 6 | 序列化/反序列化严格对齐 `ids-proto` 中的 `productv1` | +| 7 | 配置加载优先 `godotenv.Load()`,生产环境无 `.env` 时须静默降级 | +| 8 | `internal/server` 禁止 SQL;`internal/repository` 禁止 proto 响应拼装 | --- @@ -192,8 +189,7 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository |---|---| | `repository` 仅操作 `product` | [ARC-PROD-001] | | SPU/SKU 只在商品域内关联 | [ARC-PROD-002] | -| 批量商品查询去重与稳定返回 | [ARC-PROD-003] | | 价格字段统一 `int64` 分单位 | [ARC-PROD-004] | | 商品状态枚举强对齐 proto | [ARC-PROD-005] | | 配置优先 `.env` 并支持生产静默降级 | [ARC-PROD-006] | -| 商品服务作为订单算价阶段商品事实来源 | [ADR-PROD-001] | +| 商品服务作为商品主数据事实来源 | [ADR-PROD-001] | diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index fc90059..b7e2bde 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -348,34 +348,6 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* return product, skus[productID], nil } -// BatchGetProducts loads multiple SPUs and their SKU lists; missing IDs are skipped [ARC-PROD-003]. -func (r *ProductRepository) BatchGetProducts(ctx context.Context, productIDs []string) ([]*ProductRecord, map[string][]SKURecord, error) { - uniqueIDs := dedupeProductIDs(productIDs) - if len(uniqueIDs) == 0 { - return nil, map[string][]SKURecord{}, nil - } - - products, err := r.loadProductsByIDs(ctx, uniqueIDs) - if err != nil { - return nil, nil, err - } - if len(products) == 0 { - return []*ProductRecord{}, map[string][]SKURecord{}, nil - } - - foundIDs := make([]string, 0, len(products)) - for _, product := range products { - foundIDs = append(foundIDs, product.ID) - } - - skuMap, err := r.loadSKUsByProductIDs(ctx, foundIDs) - if err != nil { - return nil, nil, err - } - - return products, skuMap, nil -} - // ListCategoryProducts loads a paginated product list for a category ID. func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*ProductRecord, map[string][]SKURecord, int64, error) { parsedCategoryID, err := parseID(categoryID, "category id") @@ -662,22 +634,6 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { return &rec, nil } -func dedupeProductIDs(ids []string) []string { - seen := make(map[string]struct{}, len(ids)) - out := make([]string, 0, len(ids)) - for _, id := range ids { - if id == "" { - continue - } - if _, ok := seen[id]; ok { - continue - } - seen[id] = struct{}{} - out = append(out, id) - } - return out -} - func normalizeAttributesJSON(raw string) ([]byte, error) { if strings.TrimSpace(raw) == "" { return []byte("{}"), nil diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 50c1e25..55811ae 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -84,28 +84,6 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc }, nil } -// BatchGetProducts returns existing products for the requested IDs; missing IDs are omitted. -func (s *ProductServer) BatchGetProducts(ctx context.Context, req *productv1.BatchGetProductsRequest) (*productv1.BatchGetProductsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "request is required") - } - - products, skuMap, err := s.repo.BatchGetProducts(ctx, req.GetProductIds()) - if err != nil { - s.logger.Error("batch get products failed", zap.Strings("product_ids", req.GetProductIds()), zap.Error(err)) - return nil, status.Errorf(codes.Internal, "batch get products: %v", err) - } - - protoProducts := make([]*productv1.Product, 0, len(products)) - for _, product := range products { - protoProducts = append(protoProducts, toProtoProduct(product, skuMap[product.ID])) - } - - return &productv1.BatchGetProductsResponse{ - Products: protoProducts, - }, nil -} - // ListCategoryProducts returns a paginated product list under a category. func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { if req == nil || req.GetCategoryId() == "" { From fb6582989d8616a8d62b3533c04b747a876d0593 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 16:01:58 +0800 Subject: [PATCH 07/44] Update README to include detailed API interface specifications for CreateProduct, GetProduct, and ListCategoryProducts, enhancing clarity on request and response structures. --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/README.md b/README.md index 6c1d1e7..56d634f 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,63 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 +## 接口清单 + +当前商品服务对外暴露 3 个接口,REST 路径由 `google.api.http` 注解提供给 APISIX gRPC-Transcode 使用。 + +| RPC | REST | 请求 | 响应 | 说明 | +|---|---|---|---|---| +| `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 分页查询商品列表 | + +### `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 列表 | + +`CreateProductSKU` 字段: + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `sku_id` | `string` | 是 | SKU ID,由调用方生成 | +| `name` | `string` | 是 | SKU 名称 | +| `price` | `int64` | 是 | 售价,单位:分 | +| `available_quantity` | `int32` | 是 | 初始可售库存 | +| `attributes_json` | `string` | 否 | 规格属性 JSON 字符串 | + +### `GetProduct` + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `product_id` | `string` | 是 | 商品 SPU ID | + +响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。 + +### `ListCategoryProducts` + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `category_id` | `string` | 是 | 分类/分组节点 ID,对应 `product.product_category.id` | +| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 | +| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` | + +分页响应字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `products` | `Product[]` | 当前页商品列表 | +| `page` | `int32` | 当前页码 | +| `page_size` | `int32` | 当前每页数量 | +| `total` | `int64` | 分类/分组下商品总数 | +| `total_pages` | `int32` | 总页数 | + ## 技术栈 | 项 | 选型 | From 2e5cf31b677d14e354e707b8c74e6e350031cb5c Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 17:29:54 +0800 Subject: [PATCH 08/44] feat: add observability and metrics support - Introduced Prometheus metrics for gRPC requests and product creation. - Integrated OpenTelemetry for distributed tracing. - Updated Docker Compose configuration to expose metrics endpoint. - Enhanced architecture and development documentation with new environment variables. - Refactored configuration loading to include metrics and tracing settings. - Implemented observability package to handle tracing and metrics. - Updated product server to utilize observability features for logging and tracing. --- .env.example | 19 +- README.md | 16 ++ cmd/main.go | 48 ++++- docker-compose.yaml | 5 + docs/ARCHITECTURE.md | 8 +- docs/DEVELOPMENT.md | 8 + go.mod | 30 +++- go.sum | 57 +++++- internal/config/config.go | 23 ++- internal/observability/observability.go | 221 ++++++++++++++++++++++++ internal/server/product_server.go | 57 ++++-- 11 files changed, 451 insertions(+), 41 deletions(-) create mode 100644 internal/observability/observability.go diff --git a/.env.example b/.env.example index aec6d8b..f804ea9 100644 --- a/.env.example +++ b/.env.example @@ -1,16 +1,17 @@ -SERVER_PORT=:50051 +SERVER_PORT=:50052 POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_USER=postgres -POSTGRES_PASSWORD= -POSTGRES_DB= -TEMPORAL_HOST_PORT=localhost:7233 +POSTGRES_PASSWORD=postgres +POSTGRES_DB=ids_ecommerce +POSTGRES_SCHEMA=product +POSTGRES_SSLMODE=disable NATS_URL=nats://localhost:4222 +METRICS_PORT=:9102 +OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 +OTEL_EXPORTER_OTLP_INSECURE=true +DEPLOYMENT_ENVIRONMENT=development + # Optional -# POSTGRES_SCHEMA=order_schema -# POSTGRES_SSLMODE=disable # POSTGRES_DSN=postgres://... # full DSN override (skips assembly above) -# TEMPORAL_NAMESPACE=default -# TEMPORAL_TASK_QUEUE=ids-order-task-queue -# ORDER_PAYMENT_TIMEOUT_MINS=15 diff --git a/README.md b/README.md index 56d634f..6c20ba5 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,22 @@ cp .env.example .env | `POSTGRES_SCHEMA` | `product` | 搜索路径 | | `POSTGRES_SSLMODE` | `disable` | SSL 模式 | | `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址(首版查询链路不依赖) | +| `METRICS_PORT` | `:9102` | Prometheus 指标与 HTTP 健康检查监听地址 | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址 | +| `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接 | +| `DEPLOYMENT_ENVIRONMENT` | `development` | Trace resource 中的部署环境标签 | + +### 可观测性 + +| 能力 | 入口 / 指标 | 说明 | +|---|---|---| +| HTTP 健康检查 | `GET /healthz`, `GET /readyz` | 返回 200 前会检查 PostgreSQL 连通性 | +| 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` | 统计商品创建成功数和分类商品查询成功数 | +| 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、分类商品查询补充业务 span | +| 结构化日志 | stdout | access log 与错误日志包含 `trace_id`、`span_id`、`correlation_id` | ### 构建与运行 diff --git a/cmd/main.go b/cmd/main.go index 6394898..7ef9e39 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,17 +4,23 @@ import ( "context" "database/sql" "net" + "net/http" "os/signal" "syscall" + "time" _ "github.com/jackc/pgx/v5/stdlib" + "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.uber.org/zap" "google.golang.org/grpc" + "google.golang.org/grpc/health" + healthpb "google.golang.org/grpc/health/grpc_health_v1" "google.golang.org/grpc/reflection" 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/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/server" ) @@ -34,6 +40,18 @@ func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() + observer, shutdownTelemetry, err := observability.New(ctx, logger, cfg.OTLPEndpoint, cfg.OTELInsecure, cfg.Environment) + if err != nil { + logger.Fatal("init observability failed", zap.Error(err)) + } + defer func() { + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := shutdownTelemetry(shutdownCtx); err != nil { + logger.Error("shutdown telemetry failed", zap.Error(err)) + } + }() + db, err := sql.Open("pgx", cfg.PostgresDSN) if err != nil { logger.Fatal("open postgres failed", zap.Error(err)) @@ -52,10 +70,27 @@ func main() { logger.Fatal("ensure product schema failed", zap.Error(err)) } - productServer := server.NewProductServer(repo, logger) + metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext) + go func() { + logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort)) + if err := metricsServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + logger.Error("metrics server failed", zap.Error(err)) + stop() + } + }() - grpcServer := grpc.NewServer() + productServer := server.NewProductServer(repo, logger, observer) + + grpcServer := grpc.NewServer( + grpc.StatsHandler(otelgrpc.NewServerHandler()), + grpc.UnaryInterceptor(observer.UnaryServerInterceptor()), + ) productv1.RegisterProductServiceServer(grpcServer, productServer) + healthServer := health.NewServer() + healthServer.SetServingStatus("", healthpb.HealthCheckResponse_SERVING) + healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_SERVING) + healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_SERVING) + healthpb.RegisterHealthServer(grpcServer, healthServer) reflection.Register(grpcServer) lis, err := net.Listen("tcp", cfg.ServerPort) @@ -72,5 +107,14 @@ func main() { <-ctx.Done() logger.Info("shutting down") + + healthServer.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING) + healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING) + healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING) grpcServer.GracefulStop() + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := metricsServer.Shutdown(shutdownCtx); err != nil { + logger.Error("shutdown metrics server failed", zap.Error(err)) + } } diff --git a/docker-compose.yaml b/docker-compose.yaml index a0ccfd0..124536c 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -16,10 +16,15 @@ services: POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product} POSTGRES_SSLMODE: ${POSTGRES_SSLMODE:-disable} NATS_URL: nats://nats:4222 + METRICS_PORT: ":9102" + OTEL_EXPORTER_OTLP_ENDPOINT: http://ids-tempo:4318 + OTEL_EXPORTER_OTLP_INSECURE: "true" + DEPLOYMENT_ENVIRONMENT: ${DEPLOYMENT_ENVIRONMENT:-development} GOMODCACHE: /go/pkg/mod GOCACHE: /root/.cache/go-build ports: - "${PRODUCT_GRPC_PORT:-50052}:50052" + - "${PRODUCT_METRICS_PORT:-9102}:9102" volumes: - .:/workspace/ids-svc-product - ../ids-proto:/workspace/ids-proto:ro diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3d02c81..fd19f74 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -93,6 +93,10 @@ | `SERVER_PORT` | `:50052` | gRPC Server 监听地址。 | | `POSTGRES_DSN` | `postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product` | PostgreSQL 连接字符串,必须包含 `product` 搜索路径或由 SQL 显式限定 Schema。 | | `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址;当前商品查询主链路不依赖 NATS。 | +| `METRICS_PORT` | `:9102` | Prometheus 指标与 HTTP 健康检查监听地址。 | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址。 | +| `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接。 | +| `DEPLOYMENT_ENVIRONMENT` | `development` | OpenTelemetry resource 的部署环境标签。 | ### 4.1 `.env` 加载策略 [ARC-PROD-006] @@ -110,8 +114,10 @@ |---|---| | DB 连接失败 | `cmd/main.go` 启动阶段记录 DSN 之外的上下文并直接失败退出。 | | 单商品不存在 | repository 返回明确的 not found 语义,server 映射为 gRPC `NotFound`。 | -| 批量商品部分缺失 | 返回已存在商品集合;调用方根据业务决定是否拒单或降级。 | | SQL 执行失败 | repository 包装 product id、操作名等上下文;server 记录并映射为 gRPC `Internal`。 | +| 健康检查 | HTTP `/healthz`、`/readyz` 必须检查 PostgreSQL 连通性;gRPC 必须注册标准 Health Checking。 | +| 指标 | `/metrics` 必须暴露 runtime、RPC 请求量/耗时和商品业务指标。 | +| 链路追踪 | gRPC 自动 span 必须启用;关键业务路径补充业务 span 与错误状态。 | --- diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 40446af..2b01ad8 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -61,6 +61,10 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto SERVER_PORT=:50052 POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product NATS_URL=nats://localhost:4222 +METRICS_PORT=:9102 +OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 +OTEL_EXPORTER_OTLP_INSECURE=true +DEPLOYMENT_ENVIRONMENT=development ``` 本地开发:`cp .env.example .env`,按 infra 实际凭证修改 DSN。 @@ -78,6 +82,10 @@ NATS_URL=nats://localhost:4222 | `SERVER_PORT` | `ServerPort` | `:50052` | | `POSTGRES_DSN` | `PostgresDSN` | 见 `.env.example` | | `NATS_URL` | `NATSURL` | `nats://localhost:4222` | +| `METRICS_PORT` | `MetricsPort` | `:9102` | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `OTLPEndpoint` | `http://localhost:4318` | +| `OTEL_EXPORTER_OTLP_INSECURE` | `OTELInsecure` | `true` | +| `DEPLOYMENT_ENVIRONMENT` | `Environment` | `development` | > `NATS_URL` 当前作为后续商品事件广播的预留配置存在,首版查询链路不应强依赖 NATS 可用性。 diff --git a/go.mod b/go.mod index 04032c7..e25a1df 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,12 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto require ( github.com/jackc/pgx/v5 v5.10.0 github.com/joho/godotenv v1.5.1 + github.com/prometheus/client_golang v1.23.2 + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 + go.opentelemetry.io/otel v1.43.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 + go.opentelemetry.io/otel/sdk v1.43.0 + go.opentelemetry.io/otel/trace v1.43.0 go.uber.org/zap v1.28.0 google.golang.org/grpc v1.81.1 google.golang.org/protobuf v1.36.11 @@ -14,14 +20,30 @@ require ( ) require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.66.1 // indirect + github.com/prometheus/procfs v0.16.1 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect + go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/proto/otlp v1.10.0 // indirect go.uber.org/multierr v1.10.0 // indirect - golang.org/x/net v0.51.0 // indirect + go.yaml.in/yaml/v2 v2.4.2 // indirect + golang.org/x/net v0.52.0 // indirect golang.org/x/sync v0.20.0 // indirect golang.org/x/sys v0.42.0 // indirect - golang.org/x/text v0.34.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect + golang.org/x/text v0.35.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d // indirect ) diff --git a/go.sum b/go.sum index d350e61..bd7c6d0 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,13 @@ +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/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= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= @@ -11,6 +16,10 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -21,8 +30,28 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= +github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= +github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= +github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -30,8 +59,14 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 h1:3iZJKlCZufyRzPzlQhUIWVmfltrXuGyfjREgGP3UUjc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0/go.mod h1:/G+nUPfhq2e+qiXMGxMwumDrP5jtzU+mWN7/sjT2rak= go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= @@ -40,33 +75,39 @@ go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfC go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g= +go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= +go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= +go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= -golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= -golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4= -google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA= +google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d h1:wT2n40TBqFY6wiwazVK9/iTWbsQrgk5ZfCSVFLO9LQA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/config.go b/internal/config/config.go index 4da757c..e75b906 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -18,13 +18,20 @@ const ( defaultPostgresDB = "ids_ecommerce" defaultPostgresSchema = "product" defaultNATSURL = "nats://localhost:4222" + defaultMetricsPort = ":9102" + defaultOTLPEndpoint = "http://localhost:4318" + defaultEnvironment = "development" ) // Config holds runtime configuration loaded from environment variables. type Config struct { - ServerPort string - PostgresDSN string - NATSURL string + ServerPort string + PostgresDSN string + NATSURL string + MetricsPort string + OTLPEndpoint string + OTELInsecure bool + Environment string } // LoadConfig loads .env when present and assembles configuration from environment variables. @@ -39,9 +46,13 @@ func LoadConfig() (*Config, error) { } return &Config{ - ServerPort: getEnv("SERVER_PORT", defaultServerPort), - PostgresDSN: dsn, - NATSURL: getEnv("NATS_URL", defaultNATSURL), + ServerPort: getEnv("SERVER_PORT", defaultServerPort), + PostgresDSN: dsn, + NATSURL: getEnv("NATS_URL", defaultNATSURL), + MetricsPort: getEnv("METRICS_PORT", defaultMetricsPort), + OTLPEndpoint: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", defaultOTLPEndpoint), + OTELInsecure: getEnv("OTEL_EXPORTER_OTLP_INSECURE", "true") == "true", + Environment: getEnv("DEPLOYMENT_ENVIRONMENT", defaultEnvironment), }, nil } diff --git a/internal/observability/observability.go b/internal/observability/observability.go new file mode 100644 index 0000000..658055f --- /dev/null +++ b/internal/observability/observability.go @@ -0,0 +1,221 @@ +package observability + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prometheus/client_golang/prometheus/promhttp" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.34.0" + "go.opentelemetry.io/otel/trace" + "go.uber.org/zap" + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +const ServiceName = "ids-svc-product" + +var ( + grpcRequestsTotal = promauto.NewCounterVec( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "grpc_requests_total", + Help: "Total number of product service gRPC requests.", + }, + []string{"method", "code"}, + ) + + grpcRequestDurationSeconds = promauto.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "grpc_request_duration_seconds", + Help: "Product service gRPC request duration in seconds.", + Buckets: prometheus.DefBuckets, + }, + []string{"method", "code"}, + ) + + productsCreatedTotal = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "products_created_total", + Help: "Total number of products created successfully.", + }, + ) + + categoryProductListsTotal = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "category_product_lists_total", + Help: "Total number of successful category product list queries.", + }, + ) +) + +// Observer wires OTLP tracing and trace-aware structured logging. +type Observer struct { + logger *zap.Logger + tracer trace.Tracer +} + +// New initializes OTLP export and returns a shutdown function for the tracer provider. +func New(ctx context.Context, logger *zap.Logger, endpoint string, insecure bool, environment string) (*Observer, func(context.Context) error, error) { + if logger == nil { + logger = zap.NewNop() + } + if environment == "" { + environment = "development" + } + + opts := []otlptracehttp.Option{otlptracehttp.WithEndpointURL(endpoint)} + if insecure { + opts = append(opts, otlptracehttp.WithInsecure()) + } + exporter, err := otlptracehttp.New(ctx, opts...) + if err != nil { + return nil, nil, fmt.Errorf("create OTLP trace exporter: %w", err) + } + + res, err := resource.New(ctx, + resource.WithAttributes( + semconv.ServiceName(ServiceName), + attribute.String("deployment.environment", environment), + ), + ) + if err != nil { + return nil, nil, fmt.Errorf("create trace resource: %w", err) + } + + provider := sdktrace.NewTracerProvider( + sdktrace.WithBatcher(exporter), + sdktrace.WithResource(res), + sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), + ) + otel.SetTracerProvider(provider) + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( + propagation.TraceContext{}, propagation.Baggage{}, + )) + + o := &Observer{ + logger: logger, + tracer: provider.Tracer(ServiceName), + } + return o, provider.Shutdown, nil +} + +// NewNoop returns an observer that enriches logs and uses the global tracer provider. +func NewNoop(logger *zap.Logger) *Observer { + if logger == nil { + logger = zap.NewNop() + } + return &Observer{ + logger: logger, + tracer: otel.Tracer(ServiceName), + } +} + +// Tracer returns the service tracer; nil-safe. +func (o *Observer) Tracer() trace.Tracer { + if o == nil { + return otel.Tracer(ServiceName) + } + return o.tracer +} + +// Logger returns a logger enriched with trace_id, span_id, and correlation_id when present. +func (o *Observer) Logger(ctx context.Context) *zap.Logger { + if o == nil { + return zap.NewNop() + } + + span := trace.SpanFromContext(ctx).SpanContext() + logger := o.logger + if logger == nil { + logger = zap.NewNop() + } + if span.IsValid() { + logger = logger.With( + zap.String("trace_id", span.TraceID().String()), + zap.String("span_id", span.SpanID().String()), + ) + } + if md, ok := metadata.FromIncomingContext(ctx); ok { + for _, key := range []string{"x-request-id", "correlation-id"} { + if values := md.Get(key); len(values) > 0 && values[0] != "" { + logger = logger.With(zap.String("correlation_id", values[0])) + break + } + } + } + return logger +} + +// UnaryServerInterceptor records access logs and request metrics for every unary RPC. +func (o *Observer) UnaryServerInterceptor() grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + start := time.Now() + resp, err := handler(ctx, req) + duration := time.Since(start) + code := status.Code(err).String() + + grpcRequestsTotal.WithLabelValues(info.FullMethod, code).Inc() + grpcRequestDurationSeconds.WithLabelValues(info.FullMethod, code).Observe(duration.Seconds()) + + logger := o.Logger(ctx).With( + zap.String("grpc_method", info.FullMethod), + zap.String("grpc_code", code), + zap.Duration("duration", duration), + ) + if err != nil { + logger.Warn("grpc request completed", zap.Error(err)) + } else { + logger.Info("grpc request completed") + } + + return resp, err + } +} + +// IncProductsCreated records a successful product creation. +func IncProductsCreated() { + productsCreatedTotal.Inc() +} + +// IncCategoryProductLists records a successful category product list query. +func IncCategoryProductLists() { + categoryProductListsTotal.Inc() +} + +// MetricsServer exposes Prometheus scrape and health endpoints. +func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server { + mux := http.NewServeMux() + mux.Handle("/metrics", promhttp.Handler()) + healthHandler := func(w http.ResponseWriter, r *http.Request) { + if healthCheck != nil { + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := healthCheck(ctx); err != nil { + http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable) + return + } + } + w.WriteHeader(http.StatusOK) + } + mux.HandleFunc("/healthz", healthHandler) + mux.HandleFunc("/readyz", healthHandler) + return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second} +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 55811ae..d585a3a 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -8,6 +8,9 @@ import ( "strconv" "strings" + "go.opentelemetry.io/otel/attribute" + otelcodes "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -15,6 +18,7 @@ import ( productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" ) @@ -27,18 +31,23 @@ const ( type ProductServer struct { productv1.UnimplementedProductServiceServer - repo *repository.ProductRepository - logger *zap.Logger + repo *repository.ProductRepository + logger *zap.Logger + observer *observability.Observer } // NewProductServer constructs the gRPC product service handler. -func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger) *ProductServer { +func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, observer *observability.Observer) *ProductServer { if logger == nil { logger = zap.NewNop() } + if observer == nil { + observer = observability.NewNoop(logger) + } return &ProductServer{ - repo: repo, - logger: logger, + repo: repo, + logger: logger, + observer: observer, } } @@ -53,11 +62,20 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create return nil, status.Error(codes.InvalidArgument, err.Error()) } - createdProduct, createdSKUs, err := s.repo.CreateProductWithSKUs(ctx, product, skus) + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( + attribute.String("product.id", product.ID), + attribute.Int("product.sku_count", len(skus)), + )) + defer dbSpan.End() + + createdProduct, createdSKUs, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus) if err != nil { - s.logger.Error("create product failed", zap.String("product_id", product.ID), zap.Error(err)) + 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)) return nil, status.Errorf(codes.Internal, "create product: %v", err) } + observability.IncProductsCreated() return &productv1.CreateProductResponse{ Product: toProtoProduct(createdProduct, createdSKUs), @@ -70,12 +88,18 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc return nil, status.Error(codes.InvalidArgument, "product_id is required") } - product, skus, err := s.repo.GetProduct(ctx, req.GetProductId()) + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) + defer dbSpan.End() + + product, skus, err := s.repo.GetProduct(dbCtx, req.GetProductId()) if errors.Is(err, repository.ErrProductNotFound) { + dbSpan.SetStatus(otelcodes.Error, "product not found") return nil, status.Error(codes.NotFound, "product not found") } if err != nil { - s.logger.Error("get product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("get product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "get product: %v", err) } @@ -106,11 +130,22 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 pageSize = maxPageSize } - products, skuMap, total, err := s.repo.ListCategoryProducts(ctx, req.GetCategoryId(), page, pageSize) + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_by_category", trace.WithAttributes( + attribute.String("category.id", req.GetCategoryId()), + attribute.Int("page", int(page)), + attribute.Int("page_size", int(pageSize)), + )) + defer dbSpan.End() + + products, skuMap, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize) if err != nil { - s.logger.Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) return nil, status.Errorf(codes.Internal, "list category products: %v", err) } + dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) + observability.IncCategoryProductLists() protoProducts := make([]*productv1.Product, 0, len(products)) for _, product := range products { From 114c9578bb766a9a8d70a70986238fa2c5565d41 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 7 Jul 2026 18:28:31 +0800 Subject: [PATCH 09/44] feat: add SQL script for recreating product domain tables with necessary constraints and triggers --- scripts/sql/recreate-product-tables.sql | 226 ++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 scripts/sql/recreate-product-tables.sql diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql new file mode 100644 index 0000000..34ac606 --- /dev/null +++ b/scripts/sql/recreate-product-tables.sql @@ -0,0 +1,226 @@ +-- Manual one-shot SQL for recreating the 5 product-domain tables +-- without rebuilding the PostgreSQL data volume. +-- +-- Tables: +-- product.products +-- product.product_category +-- product.product_category_bindings +-- product.product_items +-- product.product_item_inventory +-- +-- Intended use: +-- 1. Drop the product tables manually if they still exist. +-- 2. Execute this file against the existing ids_ecommerce database. +-- +-- Drop order, if needed: +-- DROP TABLE IF EXISTS product.product_item_inventory; +-- DROP TABLE IF EXISTS product.product_category_bindings; +-- DROP TABLE IF EXISTS product.product_items; +-- DROP TABLE IF EXISTS product.product_category; +-- DROP TABLE IF EXISTS product.products; +-- +-- Example from ids-svc-product/: +-- docker cp scripts/sql/recreate-product-tables.sql ids-postgres:/tmp/recreate-product-tables.sql +-- docker exec -it ids-postgres psql -U postgres -d ids_ecommerce -f /tmp/recreate-product-tables.sql + +CREATE EXTENSION IF NOT EXISTS "pg_trgm"; + +CREATE SCHEMA IF NOT EXISTS product; + +CREATE OR REPLACE FUNCTION public.set_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TABLE IF NOT EXISTS product.products ( + id BIGINT PRIMARY KEY, + spu_no VARCHAR(100) NOT NULL, + title VARCHAR(200) NOT NULL, + selling_point VARCHAR(300), + brand_id BIGINT, + supplier_id BIGINT, + image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], + detail_html TEXT, + member_discount_enabled BOOLEAN NOT NULL DEFAULT TRUE, + goods_type SMALLINT NOT NULL DEFAULT 1, + service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], + status SMALLINT NOT NULL DEFAULT 0, + cross_border JSONB NOT NULL DEFAULT '{}'::JSONB, + freight_charge_type SMALLINT NOT NULL DEFAULT 1, + freight_fixed_amount BIGINT NOT NULL DEFAULT 0, + freight_template_id BIGINT, + sale_time_type SMALLINT NOT NULL DEFAULT 1, + scheduled_sale_time TIMESTAMPTZ, + version INTEGER NOT NULL DEFAULT 0, + deleted_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT chk_products_goods_type + CHECK (goods_type IN (1, 2, 3, 4)), + CONSTRAINT chk_products_status + CHECK (status IN (0, 1, 2, 3)), + CONSTRAINT chk_products_freight_charge_type + CHECK (freight_charge_type IN (1, 2)), + CONSTRAINT chk_products_freight_fixed_amount + CHECK (freight_fixed_amount >= 0), + CONSTRAINT chk_products_freight_template_required + CHECK (freight_charge_type <> 2 OR freight_template_id IS NOT NULL), + CONSTRAINT chk_products_sale_time_type + CHECK (sale_time_type IN (1, 2)), + CONSTRAINT chk_products_scheduled_sale_time_required + CHECK (sale_time_type <> 2 OR scheduled_sale_time IS NOT NULL), + CONSTRAINT chk_products_version + CHECK (version >= 0) +); + +COMMENT ON TABLE product.products IS '商品 SPU 主表:存储商品公共信息、分类分组、品牌、供应商、图片、商品类型、运费、开售配置和软删除状态'; +COMMENT ON COLUMN product.products.service_guarantees IS '服务保障展示快照;服务保障主数据变更时需通过业务流程刷新'; +COMMENT ON COLUMN product.products.detail_html IS '商品详情 HTML;写入或渲染前必须做 HTML Sanitization,列表接口不得读取该字段'; +COMMENT ON COLUMN product.products.version IS '乐观锁版本号,用于后台并发编辑冲突检测'; +COMMENT ON COLUMN product.products.deleted_at IS '软删除时间;NULL 表示未删除,商品禁止物理删除以保护订单和财务引用'; + +CREATE INDEX IF NOT EXISTS idx_products_title_trgm + ON product.products USING GIN (title gin_trgm_ops); + +CREATE INDEX IF NOT EXISTS idx_products_brand_status + ON product.products (brand_id, status); + +CREATE INDEX IF NOT EXISTS idx_products_status_goods_type + ON product.products (status, goods_type) + WHERE deleted_at IS NULL; + +CREATE INDEX IF NOT EXISTS idx_products_supplier_id + ON product.products (supplier_id); + +CREATE INDEX IF NOT EXISTS idx_products_goods_type + ON product.products (goods_type); + +CREATE INDEX IF NOT EXISTS idx_products_deleted_at + ON product.products (deleted_at); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no + ON product.products (spu_no) + WHERE deleted_at IS NULL; + +CREATE TABLE IF NOT EXISTS product.product_category ( + id BIGINT PRIMARY KEY, + node_type SMALLINT NOT NULL DEFAULT 0, + name VARCHAR(100) NOT NULL, + parent_id BIGINT REFERENCES product.product_category(id), + level SMALLINT NOT NULL, + image_json JSONB NOT NULL DEFAULT '[]'::JSONB, + sort_num INTEGER NOT NULL DEFAULT 0, + status SMALLINT NOT NULL DEFAULT 1, + CONSTRAINT chk_product_category_node_type + CHECK (node_type IN (0, 1)), + CONSTRAINT chk_product_category_level + CHECK (level > 0), + CONSTRAINT chk_product_category_status + CHECK (status IN (0, 1)) +); + +COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组'; +COMMENT ON COLUMN product.product_category.id IS '类别/分组节点主键'; +COMMENT ON COLUMN product.product_category.node_type IS '节点类型:0 分类,1 分组'; +COMMENT ON COLUMN product.product_category.name IS '节点展示名称'; +COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; +COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3'; +COMMENT ON COLUMN product.product_category.image_json IS '图片列表,用于小程序分类入口、分组入口展示'; +COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前'; +COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示'; + +CREATE INDEX IF NOT EXISTS idx_product_category_parent_id + ON product.product_category (parent_id); + +CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort + ON product.product_category (node_type, status, sort_num); + +CREATE TABLE IF NOT EXISTS product.product_category_bindings ( + id BIGINT PRIMARY KEY, + product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, + category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE, + CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id) +); + +COMMENT ON TABLE product.product_category_bindings IS '商品类别/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系'; +COMMENT ON COLUMN product.product_category_bindings.id IS '商品类别/分组绑定主键'; +COMMENT ON COLUMN product.product_category_bindings.product_id IS '绑定商品 SPU ID,对应 product.products.id'; +COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类/分组节点 ID,对应 product.product_category.id'; + +CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id + ON product.product_category_bindings (category_id); + +CREATE TABLE IF NOT EXISTS product.product_items ( + id BIGINT PRIMARY KEY, + product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, + sku_no VARCHAR(100), + name VARCHAR(256) NOT NULL, + price BIGINT NOT NULL CHECK (price >= 0), + 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), + deleted_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +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.attributes IS 'SKU 规格属性 JSONB,如颜色、尺寸等'; +COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用'; +COMMENT ON COLUMN product.product_items.version IS 'SKU 乐观锁版本号'; +COMMENT ON COLUMN product.product_items.deleted_at IS 'SKU 软删除时间;NULL 表示未删除'; + +CREATE INDEX IF NOT EXISTS idx_product_items_product_id + ON product.product_items (product_id) + WHERE deleted_at IS NULL; + +CREATE INDEX IF NOT EXISTS idx_product_items_price + ON product.product_items (price) + WHERE deleted_at IS NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no + ON product.product_items (sku_no) + WHERE sku_no IS NOT NULL AND deleted_at IS NULL; + +CREATE TABLE IF NOT EXISTS product.product_item_inventory ( + id BIGINT PRIMARY KEY, + sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, + available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), + locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), + sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), + version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) +); + +COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储可售库存、锁定库存和已售数量'; +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 '支付成功后的累计销量'; +COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版本号'; + +DROP TRIGGER IF EXISTS set_products_updated_at ON product.products; +CREATE TRIGGER set_products_updated_at + BEFORE UPDATE ON product.products + FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); + +DROP TRIGGER IF EXISTS set_product_items_updated_at ON product.product_items; +CREATE TRIGGER set_product_items_updated_at + BEFORE UPDATE ON product.product_items + FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); + +DROP TRIGGER IF EXISTS set_product_item_inventory_updated_at ON product.product_item_inventory; +CREATE TRIGGER set_product_item_inventory_updated_at + BEFORE UPDATE ON product.product_item_inventory + FOR EACH ROW EXECUTE FUNCTION public.set_updated_at(); + +GRANT SELECT, INSERT, UPDATE, DELETE ON product.products TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category_bindings TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory TO svc_product; From 548ed1995466f83b945830bd3640a4202c165902 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Wed, 8 Jul 2026 14:41:16 +0800 Subject: [PATCH 10/44] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E7=B1=BB=E5=88=AB=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 25 ++++++- docs/ARCHITECTURE.md | 2 + internal/observability/observability.go | 14 ++++ internal/repository/product_repository.go | 76 +++++++++++++++++++++- internal/server/product_server.go | 79 +++++++++++++++++++++++ 5 files changed, 194 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6c20ba5..985b402 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | +| `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF | 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 @@ -23,6 +24,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 | | `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 | | `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 | +| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 | ### `CreateProduct` @@ -71,6 +73,27 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `total` | `int64` | 分类/分组下商品总数 | | `total_pages` | `int32` | 总页数 | +### `ListCategoryTree` + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `only_visible` | `bool` | 否 | 为 `true` 时只返回 `status = 1` 的分类;为 `false` 时返回全部 `node_type = 0` 分类 | + +响应 `categories` 为树形分类列表。一级分类位于最外层,子分类挂载在父分类的 `children` 下。 + +`CategoryNode` 字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `category_id` | `string` | 分类节点 ID,对应 `product.product_category.id` | +| `name` | `string` | 分类展示名称 | +| `parent_id` | `string` | 父级分类 ID;一级分类为空字符串 | +| `level` | `int32` | 分类层级 | +| `image_json` | `string` | 分类图片 JSON,原样返回 | +| `sort_num` | `int32` | 同级排序值 | +| `status` | `int32` | 节点状态:`0` 隐藏,`1` 显示 | +| `children` | `CategoryNode[]` | 子分类列表 | + ## 技术栈 | 项 | 选型 | @@ -138,7 +161,7 @@ cp .env.example .env | gRPC 健康检查 | `grpc.health.v1.Health/Check` | 注册标准 gRPC Health Checking | | Prometheus 指标 | `GET /metrics` | 暴露 Go runtime、process、RPC 与商品业务指标 | | RPC 指标 | `ids_product_grpc_requests_total`, `ids_product_grpc_request_duration_seconds` | 按 `method`、`code` 维度统计请求数和耗时 | -| 商品业务指标 | `ids_product_products_created_total`, `ids_product_category_product_lists_total` | 统计商品创建成功数和分类商品查询成功数 | +| 商品业务指标 | `ids_product_products_created_total`, `ids_product_category_product_lists_total`, `ids_product_category_tree_lists_total` | 统计商品创建成功数、分类商品查询成功数和分类树查询成功数 | | 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、分类商品查询补充业务 span | | 结构化日志 | stdout | access log 与错误日志包含 `trace_id`、`span_id`、`correlation_id` | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fd19f74..4ac31a5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -75,12 +75,14 @@ | `CreateProduct` | 后台 / 运营系统 | 创建商品 SPU 及可选 SKU 列表。 | | `GetProduct` | BFF / 后台 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 | | `ListCategoryProducts` | BFF / 商城前台 | 根据分类/分组节点分页返回商品列表。 | +| `ListCategoryTree` | 微信小程序分类页 / BFF | 返回 `node_type = 0` 的商品分类树,子分类挂载在父分类 `children` 下。 | ### 3.2 查询实现约束 1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。 2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 +4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。 --- diff --git a/internal/observability/observability.go b/internal/observability/observability.go index 658055f..52d6ba9 100644 --- a/internal/observability/observability.go +++ b/internal/observability/observability.go @@ -64,6 +64,15 @@ var ( Help: "Total number of successful category product list queries.", }, ) + + categoryTreeListsTotal = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "category_tree_lists_total", + Help: "Total number of successful category tree queries.", + }, + ) ) // Observer wires OTLP tracing and trace-aware structured logging. @@ -200,6 +209,11 @@ func IncCategoryProductLists() { categoryProductListsTotal.Inc() } +// IncCategoryTreeLists records a successful category tree query. +func IncCategoryTreeLists() { + categoryTreeListsTotal.Inc() +} + // MetricsServer exposes Prometheus scrape and health endpoints. func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server { mux := http.NewServeMux() diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index b7e2bde..f5ba283 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -43,6 +43,17 @@ type SKURecord struct { UpdatedAt time.Time } +// CategoryRecord is the persistence model for product.product_category. +type CategoryRecord struct { + ID string + Name string + ParentID string + Level int32 + ImageJSON string + SortNum int32 + Status int32 +} + // ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. type ProductRepository struct { db *sql.DB @@ -419,6 +430,41 @@ LIMIT $2 OFFSET $3 return products, skuMap, total, nil } +// ListCategoryTreeNodes loads product category nodes for storefront category trees. +func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { + rows, err := r.db.QueryContext(ctx, ` +SELECT id, + name, + parent_id, + level, + image_json, + sort_num, + status +FROM product.product_category +WHERE node_type = 0 + AND ($1 = false OR status = 1) +ORDER BY level ASC, sort_num ASC, id ASC +`, onlyVisible) + if err != nil { + return nil, fmt.Errorf("query category tree nodes: %w", err) + } + defer rows.Close() + + categories := make([]*CategoryRecord, 0) + for rows.Next() { + category, err := scanCategory(rows) + if err != nil { + return nil, err + } + categories = append(categories, category) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate category tree nodes: %w", err) + } + + return categories, nil +} + func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) { products, err := r.loadProductsByIDs(ctx, []string{productID}) if err != nil { @@ -554,7 +600,7 @@ SELECT pi.id, pi.product_id, pi.name, pi.price, - COALESCE(inv.available_quantity, 0), + COALESCE(inv.sold_quantity, 0), pi.attributes, pi.created_at, pi.updated_at @@ -634,6 +680,34 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { return &rec, nil } +func scanCategory(scanner rowScanner) (*CategoryRecord, error) { + var ( + rec CategoryRecord + id int64 + parentID sql.NullInt64 + imageJSON []byte + level int16 + status int16 + ) + if err := scanner.Scan( + &id, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, + ); err != nil { + return nil, fmt.Errorf("scan category: %w", err) + } + + rec.ID = formatID(id) + if parentID.Valid { + rec.ParentID = formatID(parentID.Int64) + } + rec.Level = int32(level) + rec.ImageJSON = string(imageJSON) + if rec.ImageJSON == "" { + rec.ImageJSON = "[]" + } + rec.Status = int32(status) + return &rec, nil +} + func normalizeAttributesJSON(raw string) ([]byte, error) { if strings.TrimSpace(raw) == "" { return []byte("{}"), nil diff --git a/internal/server/product_server.go b/internal/server/product_server.go index d585a3a..314da9b 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -161,6 +161,33 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 }, nil } +// ListCategoryTree returns product category nodes as a parent-child hierarchy. +func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) { + onlyVisible := false + if req != nil { + onlyVisible = req.GetOnlyVisible() + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_category_tree", trace.WithAttributes( + attribute.Bool("category.only_visible", onlyVisible), + )) + defer dbSpan.End() + + categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("list category tree failed", zap.Bool("only_visible", onlyVisible), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "list category tree: %v", err) + } + dbSpan.SetAttributes(attribute.Int("category.result_count", len(categories))) + observability.IncCategoryTreeLists() + + return &productv1.ListCategoryTreeResponse{ + Categories: buildCategoryTree(categories), + }, nil +} + func totalPages(total int64, pageSize int32) int32 { if total <= 0 || pageSize <= 0 { return 0 @@ -289,3 +316,55 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco UpdatedAt: timestamppb.New(product.UpdatedAt), } } + +func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode { + nodes := make(map[string]*productv1.CategoryNode, len(categories)) + records := make(map[string]*repository.CategoryRecord, len(categories)) + orderedIDs := make([]string, 0, len(categories)) + + for _, category := range categories { + if category == nil || category.ID == "" { + continue + } + nodes[category.ID] = toProtoCategoryNode(category) + records[category.ID] = category + orderedIDs = append(orderedIDs, category.ID) + } + + roots := make([]*productv1.CategoryNode, 0) + for _, id := range orderedIDs { + node := nodes[id] + record := records[id] + if node == nil || record == nil { + continue + } + + parentID := record.ParentID + parent, parentExists := nodes[parentID] + parentRecord := records[parentID] + if parentID == "" || !parentExists || parentRecord == nil || parentID == id || parentRecord.Level >= record.Level { + roots = append(roots, node) + continue + } + + parent.Children = append(parent.Children, node) + } + + return roots +} + +func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.CategoryNode { + if category == nil { + return nil + } + return &productv1.CategoryNode{ + CategoryId: category.ID, + Name: category.Name, + ParentId: category.ParentID, + Level: category.Level, + ImageJson: category.ImageJSON, + SortNum: category.SortNum, + Status: category.Status, + Children: []*productv1.CategoryNode{}, + } +} From 5e74ff281643e1fac529412ef2655afb34de4cb4 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Thu, 9 Jul 2026 15:41:19 +0800 Subject: [PATCH 11/44] =?UTF-8?q?=E8=B0=83=E6=95=B4=20=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/repository/product_repository.go | 470 ++++++++++++++++++++-- internal/server/product_server.go | 89 +++- 2 files changed, 508 insertions(+), 51 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index f5ba283..ce96653 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -21,31 +21,82 @@ var ErrSKUNotFound = errors.New("sku not found") // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { - ID string - SPUNo string - Title string - SellingPoint string - Status productv1.ProductStatus - Attrs map[string]any - CreatedAt time.Time - UpdatedAt time.Time + ID string + SPUNo string + Title string + SellingPoint string + BrandID string + SupplierID string + ImageIDs []string + DetailHTML string + MemberDiscountEnabled bool + GoodsType int32 + ServiceGuarantees []string + Status productv1.ProductStatus + Attrs map[string]any + CrossBorderJSON string + FreightChargeType int32 + FreightFixedAmount int64 + FreightTemplateID string + SaleTimeType int32 + ScheduledSaleTime *time.Time + DeletedAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time } // SKURecord is the persistence model for product.product_items. type SKURecord struct { ID string ProductID string + SKUNo string Name string Price int64 AvailableQuantity int32 + LockedQuantity int32 + SoldQuantity int32 AttributesJSON string + Status int32 + DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time + Inventory *InventoryRecord +} + +// InventoryRecord is the persistence model for product.product_item_inventory. +type InventoryRecord struct { + ID string + SKUID string + AvailableQuantity int32 + LockedQuantity int32 + SoldQuantity int32 + CreatedAt time.Time + UpdatedAt time.Time +} + +// CategoryProductRecord is the product summary returned by category product lists. +type CategoryProductRecord struct { + ID string + SPUNo string + Title string + Status productv1.ProductStatus + ImageIDs []string + CreatedAt time.Time + UpdatedAt time.Time +} + +// CategoryProductSKURecord is the SKU summary returned by category product lists. +type CategoryProductSKURecord struct { + ID string + ProductID string + AvailableQuantity int32 + Price int64 } // CategoryRecord is the persistence model for product.product_category. type CategoryRecord struct { ID string + NodeType int32 Name string ParentID string Level int32 @@ -265,7 +316,7 @@ VALUES ($1, $2, $3, $4, $5::jsonb) return fmt.Errorf("insert sku %s: %w", sku.ID, err) } - if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { return err } @@ -309,7 +360,7 @@ WHERE id = $1 return ErrSKUNotFound } - if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { return err } @@ -359,8 +410,8 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* return product, skus[productID], nil } -// ListCategoryProducts loads a paginated product list for a category ID. -func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*ProductRecord, map[string][]SKURecord, int64, error) { +// ListCategoryProducts loads paginated product summaries for a category ID. +func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, map[string][]CategoryProductSKURecord, int64, error) { parsedCategoryID, err := parseID(categoryID, "category id") if err != nil { return nil, nil, 0, err @@ -384,12 +435,18 @@ WHERE b.category_id = $1 return nil, nil, 0, fmt.Errorf("count category products: %w", err) } if total == 0 { - return []*ProductRecord{}, map[string][]SKURecord{}, 0, nil + return []*CategoryProductRecord{}, map[string][]CategoryProductSKURecord{}, 0, nil } offset := int64(page-1) * int64(pageSize) rows, err := r.db.QueryContext(ctx, ` -SELECT p.id, p.spu_no, p.title, COALESCE(p.selling_point, ''), p.status, p.cross_border, p.created_at, p.updated_at +SELECT p.updated_at, + p.created_at, + p.title, + p.id, + p.spu_no, + p.status, + COALESCE(to_json(p.image_ids)::text, '[]') FROM product.products p JOIN product.product_category_bindings b ON b.product_id = p.id WHERE b.category_id = $1 @@ -402,9 +459,9 @@ LIMIT $2 OFFSET $3 } defer rows.Close() - products := make([]*ProductRecord, 0, pageSize) + products := make([]*CategoryProductRecord, 0, pageSize) for rows.Next() { - product, err := scanProduct(rows) + product, err := scanCategoryProduct(rows) if err != nil { return nil, nil, 0, err } @@ -414,7 +471,7 @@ LIMIT $2 OFFSET $3 return nil, nil, 0, fmt.Errorf("iterate category products: %w", err) } if len(products) == 0 { - return products, map[string][]SKURecord{}, total, nil + return products, map[string][]CategoryProductSKURecord{}, total, nil } foundIDs := make([]string, 0, len(products)) @@ -422,7 +479,7 @@ LIMIT $2 OFFSET $3 foundIDs = append(foundIDs, product.ID) } - skuMap, err := r.loadSKUsByProductIDs(ctx, foundIDs) + skuMap, err := r.loadCategoryProductSKUsByProductIDs(ctx, foundIDs) if err != nil { return nil, nil, 0, err } @@ -434,6 +491,7 @@ LIMIT $2 OFFSET $3 func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { rows, err := r.db.QueryContext(ctx, ` SELECT id, + node_type, name, parent_id, level, @@ -489,7 +547,27 @@ func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs [] } query := fmt.Sprintf(` -SELECT id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at +SELECT id, + spu_no, + title, + COALESCE(selling_point, ''), + brand_id, + supplier_id, + COALESCE(to_json(image_ids)::text, '[]'), + COALESCE(detail_html, ''), + member_discount_enabled, + goods_type, + COALESCE(to_json(service_guarantees)::text, '[]'), + status, + cross_border, + freight_charge_type, + freight_fixed_amount, + freight_template_id, + sale_time_type, + scheduled_sale_time, + deleted_at, + created_at, + updated_at FROM product.products WHERE id IN (%s) AND deleted_at IS NULL @@ -521,7 +599,27 @@ func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRec row := tx.QueryRowContext(ctx, ` INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) VALUES ($1, $2, $3, $4, $5, $6::jsonb) -RETURNING id, spu_no, title, COALESCE(selling_point, ''), status, cross_border, created_at, updated_at +RETURNING id, + spu_no, + title, + COALESCE(selling_point, ''), + brand_id, + supplier_id, + COALESCE(to_json(image_ids)::text, '[]'), + COALESCE(detail_html, ''), + member_discount_enabled, + goods_type, + COALESCE(to_json(service_guarantees)::text, '[]'), + status, + cross_border, + freight_charge_type, + freight_fixed_amount, + freight_template_id, + sale_time_type, + scheduled_sale_time, + deleted_at, + created_at, + updated_at `, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) createdProduct, err := scanProduct(row) @@ -549,7 +647,23 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) row := tx.QueryRowContext(ctx, ` INSERT INTO product.product_items (id, product_id, name, price, attributes) VALUES ($1, $2, $3, $4, $5::jsonb) -RETURNING id, product_id, name, price, 0, attributes, created_at, updated_at +RETURNING id, + product_id, + sku_no, + name, + price, + attributes, + status, + deleted_at, + created_at, + updated_at, + NULL::bigint, + NULL::bigint, + NULL::integer, + NULL::integer, + NULL::integer, + NULL::timestamptz, + NULL::timestamptz `, id, parsedProductID, sku.Name, sku.Price, attrs) createdSKU, err := scanSKU(row) @@ -557,25 +671,33 @@ RETURNING id, product_id, name, price, 0, attributes, created_at, updated_at return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) } - if err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + inventory, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity) + if err != nil { return nil, err } - createdSKU.AvailableQuantity = sku.AvailableQuantity + createdSKU.Inventory = inventory + if inventory != nil { + createdSKU.AvailableQuantity = inventory.AvailableQuantity + createdSKU.LockedQuantity = inventory.LockedQuantity + createdSKU.SoldQuantity = inventory.SoldQuantity + } return createdSKU, nil } -func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) error { - _, err := tx.ExecContext(ctx, ` +func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) (*InventoryRecord, error) { + row := tx.QueryRowContext(ctx, ` INSERT INTO product.product_item_inventory (id, sku_id, available_quantity) VALUES ($1, $1, $2) ON CONFLICT (sku_id) DO UPDATE SET available_quantity = EXCLUDED.available_quantity, updated_at = NOW() +RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at `, skuID, availableQuantity) + inventory, err := scanInventory(row) if err != nil { - return fmt.Errorf("upsert sku inventory %s: %w", formatID(skuID), err) + return nil, fmt.Errorf("upsert sku inventory %s: %w", formatID(skuID), err) } - return nil + return inventory, nil } func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) { @@ -598,12 +720,21 @@ func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs query := fmt.Sprintf(` SELECT pi.id, pi.product_id, + pi.sku_no, pi.name, pi.price, - COALESCE(inv.sold_quantity, 0), pi.attributes, + pi.status, + pi.deleted_at, pi.created_at, - pi.updated_at + pi.updated_at, + inv.id, + inv.sku_id, + inv.available_quantity, + inv.locked_quantity, + inv.sold_quantity, + inv.created_at, + inv.updated_at FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id WHERE pi.product_id IN (%s) @@ -631,52 +762,285 @@ ORDER BY pi.created_at ASC return result, nil } +func (r *ProductRepository) loadCategoryProductSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]CategoryProductSKURecord, error) { + result := make(map[string][]CategoryProductSKURecord, len(productIDs)) + if len(productIDs) == 0 { + return result, nil + } + + placeholders := make([]string, len(productIDs)) + args := make([]any, len(productIDs)) + for i, id := range productIDs { + parsed, err := parseID(id, "product id") + if err != nil { + return nil, err + } + placeholders[i] = fmt.Sprintf("$%d", i+1) + args[i] = parsed + } + + query := fmt.Sprintf(` +SELECT pi.id, + pi.product_id, + COALESCE(inv.available_quantity, 0), + pi.price +FROM product.product_items pi +LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id +WHERE pi.product_id IN (%s) + AND pi.deleted_at IS NULL +ORDER BY pi.created_at ASC +`, strings.Join(placeholders, ", ")) + + rows, err := r.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("query category product skus: %w", err) + } + defer rows.Close() + + for rows.Next() { + sku, err := scanCategoryProductSKU(rows) + if err != nil { + return nil, err + } + result[sku.ProductID] = append(result[sku.ProductID], *sku) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate category product skus: %w", err) + } + + return result, nil +} + type rowScanner interface { Scan(dest ...any) error } -func scanProduct(scanner rowScanner) (*ProductRecord, error) { +func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { var ( - rec ProductRecord - id int64 - status int16 - attrsJSON []byte + rec CategoryProductRecord + id int64 + status int16 + imageIDsJSON string ) if err := scanner.Scan( - &id, &rec.SPUNo, &rec.Title, &rec.SellingPoint, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &rec.UpdatedAt, + &rec.CreatedAt, + &rec.Title, + &id, + &rec.SPUNo, + &status, + &imageIDsJSON, + ); err != nil { + return nil, fmt.Errorf("scan category product: %w", err) + } + + rec.ID = formatID(id) + rec.Status = statusFromDB(status) + imageIDs, err := parseStringArrayJSON(imageIDsJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal category product image_ids: %w", err) + } + rec.ImageIDs = imageIDs + return &rec, nil +} + +func scanCategoryProductSKU(scanner rowScanner) (*CategoryProductSKURecord, error) { + var ( + rec CategoryProductSKURecord + id int64 + productID int64 + ) + if err := scanner.Scan( + &id, + &productID, + &rec.AvailableQuantity, + &rec.Price, + ); err != nil { + return nil, fmt.Errorf("scan category product sku: %w", err) + } + + rec.ID = formatID(id) + rec.ProductID = formatID(productID) + return &rec, nil +} + +func scanProduct(scanner rowScanner) (*ProductRecord, error) { + var ( + rec ProductRecord + id int64 + brandID sql.NullInt64 + supplierID sql.NullInt64 + imageIDsJSON string + serviceGuaranteesJSON string + goodsType int16 + status int16 + attrsJSON []byte + freightChargeType int16 + freightTemplateID sql.NullInt64 + saleTimeType int16 + scheduledSaleTime sql.NullTime + deletedAt sql.NullTime + ) + if err := scanner.Scan( + &id, + &rec.SPUNo, + &rec.Title, + &rec.SellingPoint, + &brandID, + &supplierID, + &imageIDsJSON, + &rec.DetailHTML, + &rec.MemberDiscountEnabled, + &goodsType, + &serviceGuaranteesJSON, + &status, + &attrsJSON, + &freightChargeType, + &rec.FreightFixedAmount, + &freightTemplateID, + &saleTimeType, + &scheduledSaleTime, + &deletedAt, + &rec.CreatedAt, + &rec.UpdatedAt, ); err != nil { return nil, fmt.Errorf("scan product: %w", err) } rec.ID = formatID(id) + if brandID.Valid { + rec.BrandID = formatID(brandID.Int64) + } + if supplierID.Valid { + rec.SupplierID = formatID(supplierID.Int64) + } + rec.GoodsType = int32(goodsType) + imageIDs, err := parseStringArrayJSON(imageIDsJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal product image_ids: %w", err) + } + rec.ImageIDs = imageIDs + serviceGuarantees, err := parseStringArrayJSON(serviceGuaranteesJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal product service_guarantees: %w", err) + } + rec.ServiceGuarantees = serviceGuarantees rec.Status = statusFromDB(status) + rec.CrossBorderJSON = string(attrsJSON) + if rec.CrossBorderJSON == "" { + rec.CrossBorderJSON = "{}" + } if len(attrsJSON) > 0 { if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil { return nil, fmt.Errorf("unmarshal product attrs: %w", err) } } + if freightTemplateID.Valid { + rec.FreightTemplateID = formatID(freightTemplateID.Int64) + } + rec.FreightChargeType = int32(freightChargeType) + rec.SaleTimeType = int32(saleTimeType) + if scheduledSaleTime.Valid { + rec.ScheduledSaleTime = timePtr(scheduledSaleTime.Time) + } + if deletedAt.Valid { + rec.DeletedAt = timePtr(deletedAt.Time) + } return &rec, nil } func scanSKU(scanner rowScanner) (*SKURecord, error) { var ( - rec SKURecord - id int64 - productID int64 - attrsJSON []byte + rec SKURecord + id int64 + productID int64 + skuNo sql.NullString + attrsJSON []byte + status int16 + deletedAt sql.NullTime + inventoryID sql.NullInt64 + inventorySKUID sql.NullInt64 + availableQuantity sql.NullInt32 + lockedQuantity sql.NullInt32 + soldQuantity sql.NullInt32 + inventoryCreatedAt sql.NullTime + inventoryUpdatedAt sql.NullTime ) if err := scanner.Scan( - &id, &productID, &rec.Name, &rec.Price, &rec.AvailableQuantity, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &id, + &productID, + &skuNo, + &rec.Name, + &rec.Price, + &attrsJSON, + &status, + &deletedAt, + &rec.CreatedAt, + &rec.UpdatedAt, + &inventoryID, + &inventorySKUID, + &availableQuantity, + &lockedQuantity, + &soldQuantity, + &inventoryCreatedAt, + &inventoryUpdatedAt, ); err != nil { return nil, fmt.Errorf("scan sku: %w", err) } rec.ID = formatID(id) rec.ProductID = formatID(productID) + if skuNo.Valid { + rec.SKUNo = skuNo.String + } rec.AttributesJSON = string(attrsJSON) if rec.AttributesJSON == "" { rec.AttributesJSON = "{}" } + rec.Status = int32(status) + if deletedAt.Valid { + rec.DeletedAt = timePtr(deletedAt.Time) + } + if inventoryID.Valid { + rec.Inventory = &InventoryRecord{ + ID: formatID(inventoryID.Int64), + SKUID: formatID(inventorySKUID.Int64), + AvailableQuantity: nullInt32Value(availableQuantity), + LockedQuantity: nullInt32Value(lockedQuantity), + SoldQuantity: nullInt32Value(soldQuantity), + } + if inventoryCreatedAt.Valid { + rec.Inventory.CreatedAt = inventoryCreatedAt.Time + } + if inventoryUpdatedAt.Valid { + rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time + } + rec.AvailableQuantity = rec.Inventory.AvailableQuantity + rec.LockedQuantity = rec.Inventory.LockedQuantity + rec.SoldQuantity = rec.Inventory.SoldQuantity + } + return &rec, nil +} + +func scanInventory(scanner rowScanner) (*InventoryRecord, error) { + var ( + rec InventoryRecord + id int64 + skuID int64 + ) + if err := scanner.Scan( + &id, + &skuID, + &rec.AvailableQuantity, + &rec.LockedQuantity, + &rec.SoldQuantity, + &rec.CreatedAt, + &rec.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan inventory: %w", err) + } + rec.ID = formatID(id) + rec.SKUID = formatID(skuID) return &rec, nil } @@ -686,16 +1050,18 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { id int64 parentID sql.NullInt64 imageJSON []byte + nodeType int16 level int16 status int16 ) if err := scanner.Scan( - &id, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, + &id, &nodeType, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, ); err != nil { return nil, fmt.Errorf("scan category: %w", err) } rec.ID = formatID(id) + rec.NodeType = int32(nodeType) if parentID.Valid { rec.ParentID = formatID(parentID.Int64) } @@ -718,6 +1084,28 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } +func parseStringArrayJSON(raw string) ([]string, error) { + if strings.TrimSpace(raw) == "" { + return []string{}, nil + } + var values []string + if err := json.Unmarshal([]byte(raw), &values); err != nil { + return nil, err + } + return values, nil +} + +func nullInt32Value(value sql.NullInt32) int32 { + if value.Valid { + return value.Int32 + } + return 0 +} + +func timePtr(value time.Time) *time.Time { + return &value +} + func statusToDB(status productv1.ProductStatus) int16 { switch status { case productv1.ProductStatus_PRODUCT_STATUS_DRAFT: diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 314da9b..3e35295 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -7,6 +7,7 @@ import ( "math" "strconv" "strings" + "time" "go.opentelemetry.io/otel/attribute" otelcodes "go.opentelemetry.io/otel/codes" @@ -147,9 +148,9 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) observability.IncCategoryProductLists() - protoProducts := make([]*productv1.Product, 0, len(products)) + protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) for _, product := range products { - protoProducts = append(protoProducts, toProtoProduct(product, skuMap[product.ID])) + protoProducts = append(protoProducts, toProtoCategoryProduct(product, skuMap[product.ID])) } return &productv1.ListCategoryProductsResponse{ @@ -298,25 +299,92 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco protoSKUs = append(protoSKUs, &productv1.SKU{ SkuId: sku.ID, ProductId: sku.ProductID, + SkuNo: sku.SKUNo, Name: sku.Name, Price: sku.Price, AvailableQuantity: sku.AvailableQuantity, + SoldQuantity: sku.SoldQuantity, AttributesJson: sku.AttributesJSON, + Status: sku.Status, + DeletedAt: timestampOrNil(sku.DeletedAt), + CreatedAt: timestamppb.New(sku.CreatedAt), + UpdatedAt: timestamppb.New(sku.UpdatedAt), + Inventory: toProtoInventory(sku.Inventory), }) } return &productv1.Product{ - ProductId: product.ID, - SpuNo: product.SPUNo, - Title: product.Title, - SellingPoint: product.SellingPoint, - Status: product.Status, - Skus: protoSKUs, - CreatedAt: timestamppb.New(product.CreatedAt), - UpdatedAt: timestamppb.New(product.UpdatedAt), + ProductId: product.ID, + SpuNo: product.SPUNo, + Title: product.Title, + SellingPoint: product.SellingPoint, + Status: product.Status, + Skus: protoSKUs, + CreatedAt: timestamppb.New(product.CreatedAt), + UpdatedAt: timestamppb.New(product.UpdatedAt), + ImageIds: product.ImageIDs, + BrandId: product.BrandID, + SupplierId: product.SupplierID, + DetailHtml: product.DetailHTML, + MemberDiscountEnabled: product.MemberDiscountEnabled, + GoodsType: product.GoodsType, + ServiceGuarantees: product.ServiceGuarantees, + CrossBorderJson: product.CrossBorderJSON, + FreightChargeType: product.FreightChargeType, + FreightFixedAmount: product.FreightFixedAmount, + FreightTemplateId: product.FreightTemplateID, + SaleTimeType: product.SaleTimeType, + ScheduledSaleTime: timestampOrNil(product.ScheduledSaleTime), + DeletedAt: timestampOrNil(product.DeletedAt), } } +func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []repository.CategoryProductSKURecord) *productv1.CategoryProduct { + if product == nil { + return nil + } + protoSKUs := make([]*productv1.CategoryProductSKU, 0, len(skus)) + for _, sku := range skus { + protoSKUs = append(protoSKUs, &productv1.CategoryProductSKU{ + SkuId: sku.ID, + AvailableQuantity: sku.AvailableQuantity, + Price: sku.Price, + }) + } + return &productv1.CategoryProduct{ + UpdatedAt: timestamppb.New(product.UpdatedAt), + CreatedAt: timestamppb.New(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Skus: protoSKUs, + } +} + +func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductItemInventory { + if inventory == nil { + return nil + } + return &productv1.ProductItemInventory{ + InventoryId: inventory.ID, + SkuId: inventory.SKUID, + AvailableQuantity: inventory.AvailableQuantity, + LockedQuantity: inventory.LockedQuantity, + SoldQuantity: inventory.SoldQuantity, + CreatedAt: timestamppb.New(inventory.CreatedAt), + UpdatedAt: timestamppb.New(inventory.UpdatedAt), + } +} + +func timestampOrNil(value *time.Time) *timestamppb.Timestamp { + if value == nil { + return nil + } + return timestamppb.New(*value) +} + func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode { nodes := make(map[string]*productv1.CategoryNode, len(categories)) records := make(map[string]*repository.CategoryRecord, len(categories)) @@ -359,6 +427,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor } return &productv1.CategoryNode{ CategoryId: category.ID, + NodeType: category.NodeType, Name: category.Name, ParentId: category.ParentID, Level: category.Level, From da065d097f2b4bc10c38ee5738a857b620ceb30d Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Fri, 10 Jul 2026 12:29:46 +0800 Subject: [PATCH 12/44] feat: add spu_no and sku_no fields to product_item_inventory table for enhanced inventory tracking --- internal/repository/product_repository.go | 11 +++++++++-- scripts/sql/recreate-product-tables.sql | 4 ++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index b7e2bde..42061c6 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -72,6 +72,8 @@ CREATE TABLE IF NOT EXISTS product.product_items ( CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, + spu_no VARCHAR(100), + sku_no VARCHAR(100), available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), @@ -520,10 +522,15 @@ RETURNING id, product_id, name, price, 0, attributes, created_at, updated_at func upsertSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) error { _, err := tx.ExecContext(ctx, ` -INSERT INTO product.product_item_inventory (id, sku_id, available_quantity) -VALUES ($1, $1, $2) +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 +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, updated_at = NOW() `, skuID, availableQuantity) if err != nil { diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 34ac606..32f24a0 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -189,6 +189,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, + spu_no VARCHAR(100), + sku_no VARCHAR(100), available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), @@ -199,6 +201,8 @@ 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.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 当前可售库存'; COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存'; COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量'; From 42419db604fc5de5cd09dd5741452b09e4b3b415 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 13:03:08 +0800 Subject: [PATCH 13/44] =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E5=95=86=E5=93=81=E5=AD=97=E6=AE=B5=E3=80=81SKU=E8=A7=84?= =?UTF-8?q?=E6=A0=BC=E6=95=B4=E7=90=86=E5=92=8C=E5=85=A5=E5=BA=93=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 19 +- internal/repository/product_repository.go | 270 +++++++++++++++++----- internal/server/product_server.go | 208 ++++++++++++++--- scripts/sql/recreate-product-tables.sql | 18 +- 4 files changed, 413 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index 985b402..07d1cb8 100644 --- a/README.md +++ b/README.md @@ -28,24 +28,9 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 ### `CreateProduct` -| 字段 | 类型 | 必填 | 说明 | -|---|---|---|---| -| `product_id` | `string` | 是 | 商品 SPU ID,由调用方生成 | -| `spu_no` | `string` | 是 | SPU 编码,未删除商品内唯一 | -| `title` | `string` | 是 | 商品标题 | -| `selling_point` | `string` | 否 | 商品卖点 | -| `status` | `ProductStatus` | 是 | 商品状态:`DRAFT` / `ON_SALE` / `OFF_SALE` | -| `skus` | `CreateProductSKU[]` | 否 | 创建时附带的 SKU 列表 | +创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 -`CreateProductSKU` 字段: - -| 字段 | 类型 | 必填 | 说明 | -|---|---|---|---| -| `sku_id` | `string` | 是 | SKU ID,由调用方生成 | -| `name` | `string` | 是 | SKU 名称 | -| `price` | `int64` | 是 | 售价,单位:分 | -| `available_quantity` | `int32` | 是 | 初始可售库存 | -| `attributes_json` | `string` | 否 | 规格属性 JSON 字符串 | +当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由数据库生成,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 ### `GetProduct` diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index ce96653..a10cf29 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -40,6 +40,7 @@ type ProductRecord struct { FreightTemplateID string SaleTimeType int32 ScheduledSaleTime *time.Time + LeafCategoryID string DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time @@ -52,10 +53,17 @@ type SKURecord struct { SKUNo string Name string Price int64 + ImageIDs []string AvailableQuantity int32 LockedQuantity int32 SoldQuantity int32 AttributesJSON string + K1 string + V1 string + K2 string + V2 string + K3 string + V3 string Status int32 DeletedAt *time.Time CreatedAt time.Time @@ -118,12 +126,26 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` +CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; + +ALTER TABLE product.products + ALTER COLUMN id SET DEFAULT nextval('product.products_id_seq'); + +ALTER TABLE product.product_category_bindings + ALTER COLUMN id SET DEFAULT nextval('product.product_category_bindings_id_seq'); + +SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); +SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, price BIGINT NOT NULL CHECK (price >= 0), + image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], attributes JSONB NOT NULL DEFAULT '{}', status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), @@ -142,6 +164,11 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); +ALTER TABLE product.product_items + ALTER COLUMN id SET DEFAULT nextval('product.product_items_id_seq'); +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; +SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; @@ -154,40 +181,29 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_ite // CreateProduct inserts a new SPU row. func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRecord) error { - attrs, err := json.Marshal(product.Attrs) - if err != nil { - return fmt.Errorf("marshal product attrs: %w", err) - } - if product.Attrs == nil { - attrs = []byte("{}") - } - - id, err := parseID(product.ID, "product id") + attrs, err := productCrossBorderJSON(product) if err != nil { return err } - _, err = r.db.ExecContext(ctx, ` -INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) -VALUES ($1, $2, $3, $4, $5, $6::jsonb) -`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) + tx, err := r.db.BeginTx(ctx, nil) if err != nil { - return fmt.Errorf("insert product %s: %w", product.ID, err) + return fmt.Errorf("begin create product: %w", err) + } + defer tx.Rollback() + + if _, err := insertProduct(ctx, tx, product, attrs); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit create product: %w", err) } return nil } // CreateProductWithSKUs inserts an SPU and its optional SKU list in one transaction. func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product ProductRecord, skus []SKURecord) (*ProductRecord, []SKURecord, error) { - attrs, err := json.Marshal(product.Attrs) - if err != nil { - return nil, nil, fmt.Errorf("marshal product attrs: %w", err) - } - if product.Attrs == nil { - attrs = []byte("{}") - } - - id, err := parseID(product.ID, "product id") + attrs, err := productCrossBorderJSON(product) if err != nil { return nil, nil, err } @@ -198,20 +214,26 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } defer tx.Rollback() - createdProduct, err := insertProduct(ctx, tx, id, product, attrs) + createdProduct, err := insertProduct(ctx, tx, product, attrs) if err != nil { return nil, nil, err } createdSKUs := make([]SKURecord, 0, len(skus)) for _, sku := range skus { - createdSKU, err := insertSKU(ctx, tx, product.ID, sku) + createdSKU, err := insertSKU(ctx, tx, createdProduct.ID, sku) if err != nil { return nil, nil, err } createdSKUs = append(createdSKUs, *createdSKU) } + if product.LeafCategoryID != "" { + if err := insertCategoryBinding(ctx, tx, createdProduct.ID, product.LeafCategoryID); err != nil { + return nil, nil, err + } + } + if err := tx.Commit(); err != nil { return nil, nil, fmt.Errorf("commit create product: %w", err) } @@ -293,10 +315,6 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error return err } - id, err := parseID(sku.ID, "sku id") - if err != nil { - return err - } productID, err := parseID(sku.ProductID, "product id") if err != nil { return err @@ -308,12 +326,14 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error } defer tx.Rollback() - _, err = tx.ExecContext(ctx, ` -INSERT INTO product.product_items (id, product_id, name, price, attributes) -VALUES ($1, $2, $3, $4, $5::jsonb) -`, id, productID, sku.Name, sku.Price, attrs) + var id int64 + err = tx.QueryRowContext(ctx, ` +INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) +RETURNING id +`, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&id) if err != nil { - return fmt.Errorf("insert sku %s: %w", sku.ID, err) + return fmt.Errorf("insert sku: %w", err) } if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { @@ -345,9 +365,9 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error res, err := tx.ExecContext(ctx, ` UPDATE product.product_items -SET name = $2, price = $3, attributes = $4::jsonb, updated_at = NOW() +SET sku_no = $2, name = $3, price = $4, image_ids = $5, attributes = $6::jsonb, status = $7, updated_at = NOW() WHERE id = $1 -`, id, sku.Name, sku.Price, attrs) +`, id, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) if err != nil { return fmt.Errorf("update sku %s: %w", sku.ID, err) } @@ -595,10 +615,40 @@ ORDER BY created_at ASC return products, nil } -func insertProduct(ctx context.Context, tx *sql.Tx, id int64, product ProductRecord, attrs []byte) (*ProductRecord, error) { +func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) { + brandID, err := nullableID(product.BrandID, "brand_id") + if err != nil { + return nil, err + } + supplierID, err := nullableID(product.SupplierID, "supplier_id") + if err != nil { + return nil, err + } + freightTemplateID, err := nullableID(product.FreightTemplateID, "freight_template_id") + if err != nil { + return nil, err + } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.products (id, spu_no, title, selling_point, status, cross_border) -VALUES ($1, $2, $3, $4, $5, $6::jsonb) +INSERT INTO product.products ( + spu_no, + title, + selling_point, + brand_id, + supplier_id, + image_ids, + detail_html, + member_discount_enabled, + goods_type, + service_guarantees, + status, + cross_border, + freight_charge_type, + freight_fixed_amount, + freight_template_id, + sale_time_type, + scheduled_sale_time +) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::jsonb, $13, $14, $15, $16, $17) RETURNING id, spu_no, title, @@ -620,11 +670,14 @@ RETURNING id, deleted_at, created_at, updated_at -`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) +`, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), + product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees), + statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, + int16(product.SaleTimeType), product.ScheduledSaleTime) createdProduct, err := scanProduct(row) if err != nil { - return nil, fmt.Errorf("insert product %s: %w", product.ID, err) + return nil, fmt.Errorf("insert product: %w", err) } return createdProduct, nil } @@ -635,23 +688,20 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) return nil, err } - id, err := parseID(sku.ID, "sku id") - if err != nil { - return nil, err - } parsedProductID, err := parseID(productID, "product id") if err != nil { return nil, err } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (id, product_id, name, price, attributes) -VALUES ($1, $2, $3, $4, $5::jsonb) +INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) RETURNING id, product_id, sku_no, name, price, + COALESCE(to_json(image_ids)::text, '[]'), attributes, status, deleted_at, @@ -664,14 +714,18 @@ RETURNING id, NULL::integer, NULL::timestamptz, NULL::timestamptz -`, id, parsedProductID, sku.Name, sku.Price, attrs) +`, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) createdSKU, err := scanSKU(row) if err != nil { - return nil, fmt.Errorf("insert sku %s: %w", sku.ID, err) + return nil, fmt.Errorf("insert sku: %w", err) } - inventory, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity) + createdSKUID, err := parseID(createdSKU.ID, "sku id") + if err != nil { + return nil, err + } + inventory, err := upsertSKUInventory(ctx, tx, createdSKUID, sku.AvailableQuantity) if err != nil { return nil, err } @@ -700,6 +754,27 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create return inventory, nil } +func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryID string) error { + parsedProductID, err := parseID(productID, "product id") + if err != nil { + return err + } + parsedCategoryID, err := parseID(categoryID, "leaf_category_id") + if err != nil { + return err + } + + _, err = tx.ExecContext(ctx, ` +INSERT INTO product.product_category_bindings (product_id, category_id) +VALUES ($1, $2) +ON CONFLICT (product_id, category_id) DO NOTHING +`, parsedProductID, parsedCategoryID) + if err != nil { + return fmt.Errorf("insert category binding: %w", err) + } + return nil +} + func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]SKURecord, error) { result := make(map[string][]SKURecord, len(productIDs)) if len(productIDs) == 0 { @@ -723,6 +798,7 @@ SELECT pi.id, pi.sku_no, pi.name, pi.price, + COALESCE(to_json(pi.image_ids)::text, '[]'), pi.attributes, pi.status, pi.deleted_at, @@ -955,6 +1031,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { id int64 productID int64 skuNo sql.NullString + imageIDsJSON string attrsJSON []byte status int16 deletedAt sql.NullTime @@ -972,6 +1049,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { &skuNo, &rec.Name, &rec.Price, + &imageIDsJSON, &attrsJSON, &status, &deletedAt, @@ -993,9 +1071,17 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { if skuNo.Valid { rec.SKUNo = skuNo.String } + imageIDs, err := parseStringArrayJSON(imageIDsJSON) + if err != nil { + return nil, fmt.Errorf("unmarshal sku image_ids: %w", err) + } + rec.ImageIDs = imageIDs rec.AttributesJSON = string(attrsJSON) if rec.AttributesJSON == "" { - rec.AttributesJSON = "{}" + rec.AttributesJSON = "[]" + } + if err := applySKUAttributes(&rec); err != nil { + return nil, err } rec.Status = int32(status) if deletedAt.Valid { @@ -1076,7 +1162,7 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { func normalizeAttributesJSON(raw string) ([]byte, error) { if strings.TrimSpace(raw) == "" { - return []byte("{}"), nil + return []byte("[]"), nil } if !json.Valid([]byte(raw)) { return nil, fmt.Errorf("invalid attributes json: %s", raw) @@ -1084,6 +1170,58 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } +func productCrossBorderJSON(product ProductRecord) ([]byte, error) { + if strings.TrimSpace(product.CrossBorderJSON) != "" { + attrs := []byte(product.CrossBorderJSON) + if !json.Valid(attrs) { + return nil, fmt.Errorf("invalid cross_border_json") + } + return attrs, nil + } + attrs, err := json.Marshal(product.Attrs) + if err != nil { + return nil, fmt.Errorf("marshal product attrs: %w", err) + } + if product.Attrs == nil { + attrs = []byte("{}") + } + return attrs, nil +} + +func applySKUAttributes(rec *SKURecord) error { + if rec == nil || strings.TrimSpace(rec.AttributesJSON) == "" { + return nil + } + if strings.TrimSpace(rec.AttributesJSON) == "{}" { + return nil + } + var attrs []map[string]string + if err := json.Unmarshal([]byte(rec.AttributesJSON), &attrs); err != nil { + return fmt.Errorf("unmarshal sku attributes: %w", err) + } + for _, item := range attrs { + if value := item["k1"]; value != "" { + rec.K1 = value + } + if value := item["v1"]; value != "" { + rec.V1 = value + } + if value := item["k2"]; value != "" { + rec.K2 = value + } + if value := item["v2"]; value != "" { + rec.V2 = value + } + if value := item["k3"]; value != "" { + rec.K3 = value + } + if value := item["v3"]; value != "" { + rec.V3 = value + } + } + return nil +} + func parseStringArrayJSON(raw string) ([]string, error) { if strings.TrimSpace(raw) == "" { return []string{}, nil @@ -1095,6 +1233,32 @@ func parseStringArrayJSON(raw string) ([]string, error) { return values, nil } +func nullableID(raw, field string) (sql.NullInt64, error) { + if strings.TrimSpace(raw) == "" { + return sql.NullInt64{}, nil + } + id, err := parseID(raw, field) + if err != nil { + return sql.NullInt64{}, err + } + return sql.NullInt64{Int64: id, Valid: true}, nil +} + +func nullString(raw string) sql.NullString { + value := strings.TrimSpace(raw) + if value == "" { + return sql.NullString{} + } + return sql.NullString{String: value, Valid: true} +} + +func stringSliceOrEmpty(values []string) []string { + if values == nil { + return []string{} + } + return values +} + func nullInt32Value(value sql.NullInt32) int32 { if value.Valid { return value.Int32 diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3e35295..9b3af7e 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -15,6 +15,7 @@ import ( "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/timestamppb" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" @@ -64,7 +65,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( - attribute.String("product.id", product.ID), + attribute.String("product.spu_no", product.SPUNo), attribute.Int("product.sku_count", len(skus)), )) defer dbSpan.End() @@ -73,7 +74,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) - s.observer.Logger(ctx).Error("create product failed", zap.String("product_id", product.ID), zap.Error(err)) + s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err)) return nil, status.Errorf(codes.Internal, "create product: %v", err) } observability.IncProductsCreated() @@ -201,11 +202,6 @@ func totalPages(total int64, pageSize int32) int32 { } func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) { - productID := strings.TrimSpace(req.GetProductId()) - if err := validatePositiveID(productID, "product_id"); err != nil { - return repository.ProductRecord{}, nil, err - } - spuNo := strings.TrimSpace(req.GetSpuNo()) if spuNo == "" { return repository.ProductRecord{}, nil, errors.New("spu_no is required") @@ -220,19 +216,53 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT } + crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo()) + if err != nil { + return repository.ProductRecord{}, nil, err + } record := repository.ProductRecord{ - ID: productID, - SPUNo: spuNo, - Title: title, - SellingPoint: req.GetSellingPoint(), - Status: statusValue, - Attrs: map[string]any{}, + SPUNo: spuNo, + Title: title, + SellingPoint: strings.TrimSpace(req.GetSellingPoint()), + BrandID: strings.TrimSpace(req.GetBrandId()), + SupplierID: strings.TrimSpace(req.GetSupplierId()), + ImageIDs: normalizeStringList(req.GetImageIds()), + DetailHTML: req.GetDetailHtml(), + MemberDiscountEnabled: req.GetMemberDiscountEnabled(), + GoodsType: defaultInt32(req.GetGoodsType(), 1), + ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()), + Status: statusValue, + CrossBorderJSON: crossBorderJSON, + FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1), + FreightFixedAmount: req.GetFreightFixedAmount(), + FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), + SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), + ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), + LeafCategoryID: strings.TrimSpace(req.GetLeafCategoryId()), + } + if record.FreightFixedAmount < 0 { + return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0") + } + if record.GoodsType < 1 || record.GoodsType > 4 { + return repository.ProductRecord{}, nil, errors.New("goods_type must be between 1 and 4") + } + if record.FreightChargeType < 1 || record.FreightChargeType > 2 { + return repository.ProductRecord{}, nil, errors.New("freight_charge_type must be 1 or 2") + } + if record.FreightChargeType == 2 && record.FreightTemplateID == "" { + return repository.ProductRecord{}, nil, errors.New("freight_template_id is required when freight_charge_type is 2") + } + if record.SaleTimeType < 1 || record.SaleTimeType > 2 { + return repository.ProductRecord{}, nil, errors.New("sale_time_type must be 1 or 2") + } + if record.SaleTimeType == 2 && record.ScheduledSaleTime == nil { + return repository.ProductRecord{}, nil, errors.New("scheduled_sale_time is required when sale_time_type is 2") } skus := make([]repository.SKURecord, 0, len(req.GetSkus())) for i, protoSKU := range req.GetSkus() { - sku, err := skuFromCreateInput(productID, protoSKU) + sku, err := skuFromCreateInput(protoSKU) if err != nil { return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) } @@ -242,20 +272,11 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P return record, skus, nil } -func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repository.SKURecord, error) { +func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, error) { if sku == nil { return repository.SKURecord{}, errors.New("sku is required") } - skuID := strings.TrimSpace(sku.GetSkuId()) - if err := validatePositiveID(skuID, "sku_id"); err != nil { - return repository.SKURecord{}, err - } - - name := strings.TrimSpace(sku.GetName()) - if name == "" { - return repository.SKURecord{}, errors.New("name is required") - } if sku.GetPrice() < 0 { return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") } @@ -263,21 +284,142 @@ func skuFromCreateInput(productID string, sku *productv1.CreateProductSKU) (repo return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0") } - attrs := strings.TrimSpace(sku.GetAttributesJson()) - if attrs != "" && !json.Valid([]byte(attrs)) { - return repository.SKURecord{}, errors.New("attributes_json must be valid json") + attrs, name, err := buildSKUAttributesAndName(sku) + if err != nil { + return repository.SKURecord{}, err + } + statusValue := sku.GetStatus() + if statusValue == 0 { + statusValue = 1 + } + if statusValue < 0 || statusValue > 1 { + return repository.SKURecord{}, errors.New("status must be 0 or 1") } return repository.SKURecord{ - ID: skuID, - ProductID: productID, + SKUNo: strings.TrimSpace(sku.GetSkuNo()), Name: name, Price: sku.GetPrice(), + ImageIDs: normalizeStringList(sku.GetImageIds()), AvailableQuantity: sku.GetAvailableQuantity(), AttributesJSON: attrs, + K1: strings.TrimSpace(sku.GetK1()), + V1: strings.TrimSpace(sku.GetV1()), + K2: strings.TrimSpace(sku.GetK2()), + V2: strings.TrimSpace(sku.GetV2()), + K3: strings.TrimSpace(sku.GetK3()), + V3: strings.TrimSpace(sku.GetV3()), + Status: statusValue, }, nil } +func buildSKUAttributesAndName(sku *productv1.CreateProductSKU) (string, string, error) { + specs := []struct { + keyField string + valueField string + key string + value string + }{ + {keyField: "k1", valueField: "v1", key: strings.TrimSpace(sku.GetK1()), value: strings.TrimSpace(sku.GetV1())}, + {keyField: "k2", valueField: "v2", key: strings.TrimSpace(sku.GetK2()), value: strings.TrimSpace(sku.GetV2())}, + {keyField: "k3", valueField: "v3", key: strings.TrimSpace(sku.GetK3()), value: strings.TrimSpace(sku.GetV3())}, + } + + attrs := make([]map[string]string, 0, len(specs)) + nameParts := make([]string, 0, len(specs)) + foundEmpty := false + for _, spec := range specs { + if spec.key == "" && spec.value == "" { + foundEmpty = true + continue + } + if foundEmpty { + return "", "", errors.New("sku specs must be filled in order from k1/v1 to k3/v3") + } + if spec.key == "" || spec.value == "" { + return "", "", errors.New(spec.keyField + "/" + spec.valueField + " must be provided together") + } + attrs = append(attrs, map[string]string{ + spec.keyField: spec.key, + spec.valueField: spec.value, + }) + nameParts = append(nameParts, spec.value) + } + if len(attrs) == 0 { + return "", "", errors.New("at least one sku spec k1/v1 is required") + } + + attrsJSON, err := json.Marshal(attrs) + if err != nil { + return "", "", err + } + return string(attrsJSON), strings.Join(nameParts, " "), nil +} + +func crossBorderJSONFromProto(info *productv1.CrossBorderInfo) (string, error) { + if info == nil { + return "{}", nil + } + if info.GetCustomsTaxRateBps() < 0 { + return "", errors.New("cross_border_info.customs_tax_rate_bps must be greater than or equal to 0") + } + switch info.GetLogisticsMode() { + case productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_UNSPECIFIED, + productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_BONDED_IMPORT, + productv1.CrossBorderLogisticsMode_CROSS_BORDER_LOGISTICS_MODE_OVERSEAS_DIRECT_MAIL: + default: + return "", errors.New("cross_border_info.logistics_mode is invalid") + } + + marshalOptions := protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true} + raw, err := marshalOptions.Marshal(info) + if err != nil { + return "", err + } + return string(raw), nil +} + +func toProtoCrossBorderInfo(raw string) *productv1.CrossBorderInfo { + if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" { + return nil + } + info := &productv1.CrossBorderInfo{} + unmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true} + if err := unmarshalOptions.Unmarshal([]byte(raw), info); err != nil { + return nil + } + return info +} + +func normalizeStringList(values []string) []string { + if len(values) == 0 { + return []string{} + } + out := make([]string, 0, len(values)) + for _, value := range values { + trimmed := strings.TrimSpace(value) + if trimmed != "" { + out = append(out, trimmed) + } + } + return out +} + +func defaultInt32(value, fallback int32) int32 { + if value == 0 { + return fallback + } + return value +} + +func timestampToTime(value *timestamppb.Timestamp) *time.Time { + if value == nil { + return nil + } + t := value.AsTime() + return &t +} + func validatePositiveID(raw, field string) error { if raw == "" { return errors.New(field + " is required") @@ -306,6 +448,13 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco SoldQuantity: sku.SoldQuantity, AttributesJson: sku.AttributesJSON, Status: sku.Status, + ImageIds: sku.ImageIDs, + K1: sku.K1, + V1: sku.V1, + K2: sku.K2, + V2: sku.V2, + K3: sku.K3, + V3: sku.V3, DeletedAt: timestampOrNil(sku.DeletedAt), CreatedAt: timestamppb.New(sku.CreatedAt), UpdatedAt: timestamppb.New(sku.UpdatedAt), @@ -330,6 +479,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco GoodsType: product.GoodsType, ServiceGuarantees: product.ServiceGuarantees, CrossBorderJson: product.CrossBorderJSON, + CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), FreightChargeType: product.FreightChargeType, FreightFixedAmount: product.FreightFixedAmount, FreightTemplateId: product.FreightTemplateID, diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 34ac606..44490fc 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -27,6 +27,10 @@ CREATE EXTENSION IF NOT EXISTS "pg_trgm"; CREATE SCHEMA IF NOT EXISTS product; +CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; +CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; + CREATE OR REPLACE FUNCTION public.set_updated_at() RETURNS TRIGGER AS $$ BEGIN @@ -36,7 +40,7 @@ END; $$ LANGUAGE plpgsql; CREATE TABLE IF NOT EXISTS product.products ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.products_id_seq'), spu_no VARCHAR(100) NOT NULL, title VARCHAR(200) NOT NULL, selling_point VARCHAR(300), @@ -105,6 +109,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no ON product.products (spu_no) WHERE deleted_at IS NULL; +SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_category ( id BIGINT PRIMARY KEY, node_type SMALLINT NOT NULL DEFAULT 0, @@ -139,7 +145,7 @@ CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort ON product.product_category (node_type, status, sort_num); CREATE TABLE IF NOT EXISTS product.product_category_bindings ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.product_category_bindings_id_seq'), product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE, CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id) @@ -153,12 +159,15 @@ COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类 CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id ON product.product_category_bindings (category_id); +SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY, + id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, price BIGINT NOT NULL CHECK (price >= 0), + image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], attributes JSONB NOT NULL DEFAULT '{}', status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), @@ -169,6 +178,7 @@ CREATE TABLE IF NOT EXISTS product.product_items ( COMMENT ON TABLE product.product_items IS '商品 SKU 明细表:存储具体可售规格、价格和规格属性;库存统一存储在 product.product_item_inventory'; COMMENT ON COLUMN product.product_items.price IS 'SKU 售价,单位:分'; +COMMENT ON COLUMN product.product_items.image_ids IS 'SKU 图片 ID 列表'; COMMENT ON COLUMN product.product_items.attributes IS 'SKU 规格属性 JSONB,如颜色、尺寸等'; COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用'; COMMENT ON COLUMN product.product_items.version IS 'SKU 乐观锁版本号'; @@ -186,6 +196,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items (sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; +SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); + CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, From 517f629d76a82c28d25dd344c632cc4b1923ee33 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Fri, 10 Jul 2026 15:56:42 +0800 Subject: [PATCH 14/44] feat: integrate Snowflake ID generation for product and SKU creation - Added a new ID generator using the Snowflake algorithm to create unique identifiers for products and SKUs. - Updated the product server to utilize the ID generator for assigning IDs during product and SKU creation. - Refactored the product repository to accommodate the new ID handling logic. - Introduced unit tests for the ID generator to ensure correct functionality and error handling. --- cmd/main.go | 8 ++++- go.mod | 1 + go.sum | 2 ++ internal/idgen/snowflake.go | 41 +++++++++++++++++++++++ internal/idgen/snowflake_test.go | 28 ++++++++++++++++ internal/repository/product_repository.go | 32 ++++++++++++------ internal/server/product_server.go | 12 ++++++- 7 files changed, 112 insertions(+), 12 deletions(-) create mode 100644 internal/idgen/snowflake.go create mode 100644 internal/idgen/snowflake_test.go diff --git a/cmd/main.go b/cmd/main.go index 7ef9e39..423fa95 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -20,6 +20,7 @@ import ( productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/config" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/server" @@ -70,6 +71,11 @@ func main() { logger.Fatal("ensure product schema failed", zap.Error(err)) } + idGenerator, err := idgen.NewFromEnv() + if err != nil { + logger.Fatal("init snowflake id generator failed", zap.Error(err)) + } + metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext) go func() { logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort)) @@ -79,7 +85,7 @@ func main() { } }() - productServer := server.NewProductServer(repo, logger, observer) + productServer := server.NewProductServer(repo, idGenerator, logger, observer) grpcServer := grpc.NewServer( grpc.StatsHandler(otelgrpc.NewServerHandler()), diff --git a/go.mod b/go.mod index e25a1df..72fadc2 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.26.4 replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto require ( + github.com/bwmarrin/snowflake v0.3.0 github.com/jackc/pgx/v5 v5.10.0 github.com/joho/godotenv v1.5.1 github.com/prometheus/client_golang v1.23.2 diff --git a/go.sum b/go.sum index bd7c6d0..fae7067 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0= +github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= diff --git a/internal/idgen/snowflake.go b/internal/idgen/snowflake.go new file mode 100644 index 0000000..9ed90e4 --- /dev/null +++ b/internal/idgen/snowflake.go @@ -0,0 +1,41 @@ +package idgen + +import ( + "fmt" + "os" + "strconv" + + "github.com/bwmarrin/snowflake" +) + +// Generator creates 64-bit, time-sortable Snowflake IDs. +type Generator struct { + node *snowflake.Node +} + +// NewFromEnv creates a generator using SNOWFLAKE_WORKER_ID, defaulting to 1. +func NewFromEnv() (*Generator, error) { + workerID := int64(1) + if raw := os.Getenv("SNOWFLAKE_WORKER_ID"); raw != "" { + parsed, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + return nil, fmt.Errorf("parse SNOWFLAKE_WORKER_ID: %w", err) + } + workerID = parsed + } + node, err := snowflake.NewNode(workerID) + if err != nil { + return nil, fmt.Errorf("create snowflake node: %w", err) + } + return &Generator{node: node}, nil +} + +// Next returns a new Snowflake ID. +func (g *Generator) Next() int64 { + return g.node.Generate().Int64() +} + +// NextString returns a decimal string representation of Next. +func (g *Generator) NextString() string { + return strconv.FormatInt(g.Next(), 10) +} diff --git a/internal/idgen/snowflake_test.go b/internal/idgen/snowflake_test.go new file mode 100644 index 0000000..2f42d95 --- /dev/null +++ b/internal/idgen/snowflake_test.go @@ -0,0 +1,28 @@ +package idgen + +import ( + "strconv" + "testing" +) + +func TestGeneratorNextString(t *testing.T) { + t.Setenv("SNOWFLAKE_WORKER_ID", "1") + + g, err := NewFromEnv() + if err != nil { + t.Fatalf("NewFromEnv() error = %v", err) + } + + id := g.NextString() + if _, err := strconv.ParseInt(id, 10, 64); err != nil { + t.Fatalf("NextString() = %q, want decimal int64: %v", id, err) + } +} + +func TestNewFromEnvRejectsInvalidWorkerID(t *testing.T) { + t.Setenv("SNOWFLAKE_WORKER_ID", "1024") + + if _, err := NewFromEnv(); err == nil { + t.Fatal("NewFromEnv() error = nil, want error") + } +} diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index a10cf29..c9e55ad 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -319,6 +319,10 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error if err != nil { return err } + skuID, err := parseID(sku.ID, "sku id") + if err != nil { + return err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { @@ -326,17 +330,16 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error } defer tx.Rollback() - var id int64 err = tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) -VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) +INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8) RETURNING id -`, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&id) +`, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID) if err != nil { return fmt.Errorf("insert sku: %w", err) } - if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := upsertSKUInventory(ctx, tx, skuID, sku.AvailableQuantity); err != nil { return err } @@ -616,6 +619,10 @@ ORDER BY created_at ASC } func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) { + id, err := parseID(product.ID, "product id") + if err != nil { + return nil, err + } brandID, err := nullableID(product.BrandID, "brand_id") if err != nil { return nil, err @@ -630,6 +637,7 @@ func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs } row := tx.QueryRowContext(ctx, ` INSERT INTO product.products ( + id, spu_no, title, selling_point, @@ -648,7 +656,7 @@ INSERT INTO product.products ( sale_time_type, scheduled_sale_time ) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::jsonb, $13, $14, $15, $16, $17) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18) RETURNING id, spu_no, title, @@ -670,7 +678,7 @@ RETURNING id, deleted_at, created_at, updated_at -`, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), +`, id, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees), statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, int16(product.SaleTimeType), product.ScheduledSaleTime) @@ -687,6 +695,10 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) if err != nil { return nil, err } + id, err := parseID(sku.ID, "sku id") + if err != nil { + return nil, err + } parsedProductID, err := parseID(productID, "product id") if err != nil { @@ -694,8 +706,8 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) -VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) +INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8) RETURNING id, product_id, sku_no, @@ -714,7 +726,7 @@ RETURNING id, NULL::integer, NULL::timestamptz, NULL::timestamptz -`, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) +`, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) createdSKU, err := scanSKU(row) if err != nil { diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 9b3af7e..3b262c7 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -20,6 +20,7 @@ import ( productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" ) @@ -34,12 +35,13 @@ type ProductServer struct { productv1.UnimplementedProductServiceServer repo *repository.ProductRepository + idgen *idgen.Generator logger *zap.Logger observer *observability.Observer } // NewProductServer constructs the gRPC product service handler. -func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, observer *observability.Observer) *ProductServer { +func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer { if logger == nil { logger = zap.NewNop() } @@ -48,6 +50,7 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, ob } return &ProductServer{ repo: repo, + idgen: idGenerator, logger: logger, observer: observer, } @@ -63,6 +66,13 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + product.ID = s.idgen.NextString() + for i := range skus { + skus[i].ID = s.idgen.NextString() + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( attribute.String("product.spu_no", product.SPUNo), From 1c89c4a11fe8881980a0a13dca0a214067b89368 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 16:31:07 +0800 Subject: [PATCH 15/44] feat(product): switch product IDs to application snowflake generation --- .env.example | 1 + README.md | 56 +++++++++++++++++++++-- cmd/main.go | 10 ++-- docker-compose.yaml | 1 + internal/repository/product_repository.go | 31 ++++++------- internal/server/product_server.go | 3 ++ scripts/sql/recreate-product-tables.sql | 16 ++----- 7 files changed, 80 insertions(+), 38 deletions(-) diff --git a/.env.example b/.env.example index f804ea9..1d7d2e1 100644 --- a/.env.example +++ b/.env.example @@ -12,6 +12,7 @@ METRICS_PORT=:9102 OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 OTEL_EXPORTER_OTLP_INSECURE=true DEPLOYMENT_ENVIRONMENT=development +SNOWFLAKE_WORKER_ID=1 # Optional # POSTGRES_DSN=postgres://... # full DSN override (skips assembly above) diff --git a/README.md b/README.md index 07d1cb8..de22173 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,56 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 -当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由数据库生成,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 +当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 + +创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成: + +| ID | 生成方式 | 写入位置 | +|---|---|---| +| `product_id` | 服务内 Snowflake 生成 | `product.products.id` | +| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` | +| `inventory_id` | 复用对应 `sku_id` | `product.product_item_inventory.id` | +| 分类绑定 ID | 传入 `leaf_category_id` 时服务内 Snowflake 生成 | `product.product_category_bindings.id` | + +常用请求字段: + +| 字段 | 必填 | 说明 | +|---|---:|---| +| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 | +| `title` | 是 | 商品标题 | +| `selling_point` | 否 | 商品卖点 | +| `leaf_category_id` | 否 | 已存在的分类/分组节点 ID;传入后会写入分类绑定 | +| `image_ids` | 否 | 商品图片 ID 列表 | +| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID | +| `status` | 否 | 未传时默认草稿 | +| `goods_type` | 否 | 未传时默认 `1` | +| `freight_charge_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `freight_template_id` | +| `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` | +| `skus` | 否 | SKU 列表 | + +`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 名称由规格值拼接,例如 `500g 原味`。 + +最小示例: + +```json +{ + "spu_no": "SPU202607100001", + "title": "澳洲和牛家庭装", + "selling_point": "原切谷饲,冷链到家", + "leaf_category_id": "726390485721088000", + "skus": [ + { + "sku_no": "SKU20260710000101", + "price": 12800, + "available_quantity": 100, + "k1": "规格", + "v1": "1kg" + } + ] +} +``` + +响应中的 `product.product_id` 和 `product.skus[].sku_id` 是服务生成后的最终主键 ID。 ### `GetProduct` @@ -137,6 +186,7 @@ cp .env.example .env | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址 | | `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接 | | `DEPLOYMENT_ENVIRONMENT` | `development` | Trace resource 中的部署环境标签 | +| `SNOWFLAKE_WORKER_ID` | `1` | Snowflake worker ID;同一部署环境内不同服务实例必须使用不同值 | ### 可观测性 @@ -170,8 +220,8 @@ grpcurl -plaintext localhost:50052 list grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct -# 创建商品 -grpcurl -plaintext -d '{"product_id":"","spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ +# 创建商品;product_id 和 sku_id 由服务生成 +grpcurl -plaintext -d '{"spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ localhost:50052 ids.product.v1.ProductService/CreateProduct # 分页查询分类商品 diff --git a/cmd/main.go b/cmd/main.go index 423fa95..69499ab 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -38,6 +38,11 @@ func main() { logger.Fatal("load config failed", zap.Error(err)) } + idGenerator, err := idgen.NewFromEnv() + if err != nil { + logger.Fatal("init snowflake id generator failed", zap.Error(err)) + } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() @@ -71,11 +76,6 @@ func main() { logger.Fatal("ensure product schema failed", zap.Error(err)) } - idGenerator, err := idgen.NewFromEnv() - if err != nil { - logger.Fatal("init snowflake id generator failed", zap.Error(err)) - } - metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext) go func() { logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort)) diff --git a/docker-compose.yaml b/docker-compose.yaml index 124536c..c65f107 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -20,6 +20,7 @@ services: OTEL_EXPORTER_OTLP_ENDPOINT: http://ids-tempo:4318 OTEL_EXPORTER_OTLP_INSECURE: "true" DEPLOYMENT_ENVIRONMENT: ${DEPLOYMENT_ENVIRONMENT:-development} + SNOWFLAKE_WORKER_ID: ${SNOWFLAKE_WORKER_ID:-1} GOMODCACHE: /go/pkg/mod GOCACHE: /root/.cache/go-build ports: diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index c9e55ad..59e44c4 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -41,6 +41,7 @@ type ProductRecord struct { SaleTimeType int32 ScheduledSaleTime *time.Time LeafCategoryID string + CategoryBindingID string DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time @@ -126,21 +127,14 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` -CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; - ALTER TABLE product.products - ALTER COLUMN id SET DEFAULT nextval('product.products_id_seq'); + ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_category_bindings - ALTER COLUMN id SET DEFAULT nextval('product.product_category_bindings_id_seq'); - -SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); -SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); + ALTER COLUMN id DROP DEFAULT; CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), + id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, @@ -165,10 +159,9 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); ALTER TABLE product.product_items - ALTER COLUMN id SET DEFAULT nextval('product.product_items_id_seq'); + ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; -SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; @@ -229,7 +222,7 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } if product.LeafCategoryID != "" { - if err := insertCategoryBinding(ctx, tx, createdProduct.ID, product.LeafCategoryID); err != nil { + if err := insertCategoryBinding(ctx, tx, product.CategoryBindingID, createdProduct.ID, product.LeafCategoryID); err != nil { return nil, nil, err } } @@ -766,7 +759,11 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create return inventory, nil } -func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryID string) error { +func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID, categoryID string) error { + parsedBindingID, err := parseID(bindingID, "category binding id") + if err != nil { + return err + } parsedProductID, err := parseID(productID, "product id") if err != nil { return err @@ -777,10 +774,10 @@ func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryI } _, err = tx.ExecContext(ctx, ` -INSERT INTO product.product_category_bindings (product_id, category_id) -VALUES ($1, $2) +INSERT INTO product.product_category_bindings (id, product_id, category_id) +VALUES ($1, $2, $3) ON CONFLICT (product_id, category_id) DO NOTHING -`, parsedProductID, parsedCategoryID) +`, parsedBindingID, parsedProductID, parsedCategoryID) if err != nil { return fmt.Errorf("insert category binding: %w", err) } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3b262c7..3a5cfaf 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -73,6 +73,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create for i := range skus { skus[i].ID = s.idgen.NextString() } + if product.LeafCategoryID != "" { + product.CategoryBindingID = s.idgen.NextString() + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( attribute.String("product.spu_no", product.SPUNo), diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 44490fc..43a2173 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -27,10 +27,6 @@ CREATE EXTENSION IF NOT EXISTS "pg_trgm"; CREATE SCHEMA IF NOT EXISTS product; -CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; - CREATE OR REPLACE FUNCTION public.set_updated_at() RETURNS TRIGGER AS $$ BEGIN @@ -40,7 +36,7 @@ END; $$ LANGUAGE plpgsql; CREATE TABLE IF NOT EXISTS product.products ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.products_id_seq'), + id BIGINT PRIMARY KEY, spu_no VARCHAR(100) NOT NULL, title VARCHAR(200) NOT NULL, selling_point VARCHAR(300), @@ -109,8 +105,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no ON product.products (spu_no) WHERE deleted_at IS NULL; -SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_category ( id BIGINT PRIMARY KEY, node_type SMALLINT NOT NULL DEFAULT 0, @@ -145,7 +139,7 @@ CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort ON product.product_category (node_type, status, sort_num); CREATE TABLE IF NOT EXISTS product.product_category_bindings ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_category_bindings_id_seq'), + id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE, CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id) @@ -159,10 +153,8 @@ COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类 CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id ON product.product_category_bindings (category_id); -SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), + id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, sku_no VARCHAR(100), name VARCHAR(256) NOT NULL, @@ -196,8 +188,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items (sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; -SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, From d0f0aea15f4b0b9f826aa4a94a33ca64ccc5d5f0 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 17:29:04 +0800 Subject: [PATCH 16/44] feat(product): return compact create product result --- README.md | 16 +++++++++++++++- internal/server/product_server.go | 18 ++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index de22173..3ff3888 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,21 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 } ``` -响应中的 `product.product_id` 和 `product.skus[].sku_id` 是服务生成后的最终主键 ID。 +响应只返回创建结果摘要,字段结构如下: + +```json +{ + "data": { + "item_id": 726390485721088000, + "title": "澳洲和牛家庭装" + }, + "success": true, + "code": 0, + "message": "success" +} +``` + +其中 `data.item_id` 是服务生成后的商品主键 ID,`data.title` 是商品标题。 ### `GetProduct` diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3a5cfaf..6887b5e 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -83,7 +83,7 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create )) defer dbSpan.End() - createdProduct, createdSKUs, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus) + createdProduct, _, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -92,8 +92,22 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create } observability.IncProductsCreated() + itemID, err := strconv.ParseInt(createdProduct.ID, 10, 64) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("parse created product id failed", zap.String("product_id", createdProduct.ID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "parse created product id: %v", err) + } + return &productv1.CreateProductResponse{ - Product: toProtoProduct(createdProduct, createdSKUs), + Data: &productv1.CreateProductData{ + ItemId: itemID, + Title: createdProduct.Title, + }, + Success: true, + Code: 0, + Message: "success", }, nil } From 2fa8872603268fc4ca45885389b619dfa158708d Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 19:04:45 +0800 Subject: [PATCH 17/44] fix(product): tighten SKU attributes parsing for product query --- internal/repository/product_repository.go | 63 ++++++++++++++++++++--- internal/server/product_server.go | 3 ++ 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 59e44c4..08e99d4 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -10,6 +10,8 @@ import ( "strings" "time" + "github.com/jackc/pgx/v5/pgconn" + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" ) @@ -19,6 +21,9 @@ var ErrProductNotFound = errors.New("product not found") // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") +// ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number. +var ErrDuplicateSPUNo = errors.New("spu_no already exists") + // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { ID string @@ -678,11 +683,22 @@ RETURNING id, createdProduct, err := scanProduct(row) if err != nil { + if isPostgresConstraintError(err, "23505", "uq_products_spu_no") { + return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, product.SPUNo) + } return nil, fmt.Errorf("insert product: %w", err) } return createdProduct, nil } +func isPostgresConstraintError(err error, code, constraint string) bool { + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) { + return false + } + return pgErr.Code == code && pgErr.ConstraintName == constraint +} + func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) { attrs, err := normalizeAttributesJSON(sku.AttributesJSON) if err != nil { @@ -1198,15 +1214,12 @@ func productCrossBorderJSON(product ProductRecord) ([]byte, error) { } func applySKUAttributes(rec *SKURecord) error { - if rec == nil || strings.TrimSpace(rec.AttributesJSON) == "" { + if rec == nil { return nil } - if strings.TrimSpace(rec.AttributesJSON) == "{}" { - return nil - } - var attrs []map[string]string - if err := json.Unmarshal([]byte(rec.AttributesJSON), &attrs); err != nil { - return fmt.Errorf("unmarshal sku attributes: %w", err) + attrs, err := parseSKUAttributes(rec.AttributesJSON) + if err != nil { + return err } for _, item := range attrs { if value := item["k1"]; value != "" { @@ -1231,6 +1244,42 @@ func applySKUAttributes(rec *SKURecord) error { return nil } +func parseSKUAttributes(raw string) ([]map[string]string, error) { + raw = strings.TrimSpace(raw) + if raw == "" || raw == "{}" || raw == "null" { + return nil, nil + } + var attrs []map[string]string + if err := json.Unmarshal([]byte(raw), &attrs); err == nil { + return attrs, nil + } + + var attr map[string]any + if err := json.Unmarshal([]byte(raw), &attr); err != nil { + return nil, fmt.Errorf("unmarshal sku attributes: %w", err) + } + if isEmptySKUAttributeObject(attr) { + return nil, nil + } + return nil, fmt.Errorf("unmarshal sku attributes: expected array, got object") +} + +func isEmptySKUAttributeObject(attr map[string]any) bool { + if len(attr) == 0 { + return true + } + for _, value := range attr { + if value == nil { + continue + } + if s, ok := value.(string); ok && strings.TrimSpace(s) == "" { + continue + } + return false + } + return true +} + func parseStringArrayJSON(raw string) ([]string, error) { if strings.TrimSpace(raw) == "" { return []string{}, nil diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 6887b5e..29716c1 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -88,6 +88,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err)) + if errors.Is(err, repository.ErrDuplicateSPUNo) { + return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo) + } return nil, status.Errorf(codes.Internal, "create product: %v", err) } observability.IncProductsCreated() From ae940225c4275f39135e4c0a4a1fc7ee4b3efdbb Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Mon, 13 Jul 2026 14:12:05 +0800 Subject: [PATCH 18/44] feat(product): return product time fields as millisecond timestamp strings --- README.md | 4 ++- internal/server/product_server.go | 41 +++++++++++++++++-------------- 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 3ff3888..54c47c2 100644 --- a/README.md +++ b/README.md @@ -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` | 字段 | 类型 | 必填 | 说明 | diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 29716c1..d5e73c7 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -450,6 +450,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 +497,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 +511,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 +526,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 +544,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 +565,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)) From a7d3929855aecee1912ce01ce90faf42c3b8dcb7 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Mon, 13 Jul 2026 15:01:08 +0800 Subject: [PATCH 19/44] feat(product): implement category/group APIs and inventory snowflake IDs --- README.md | 4 +- internal/repository/product_repository.go | 192 ++++++++++++++++- internal/server/product_server.go | 246 ++++++++++++++++++++++ scripts/sql/recreate-product-tables.sql | 1 + 4 files changed, 435 insertions(+), 8 deletions(-) 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 '支付成功后的累计销量'; From e1ebe15bba2e5ef5fbabda0c7dfe4b037ead5b88 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Mon, 13 Jul 2026 17:23:36 +0800 Subject: [PATCH 20/44] chore(product): drop dev schema compatibility columns --- internal/repository/product_repository.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index fa60389..0b06cf4 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -169,10 +169,6 @@ ALTER TABLE product.product_items ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; -ALTER TABLE product.product_item_inventory - ADD COLUMN IF NOT EXISTS spu_no VARCHAR(100); -ALTER TABLE product.product_item_inventory - ADD COLUMN IF NOT EXISTS sku_no VARCHAR(100); CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; From a6bca494f46ed03531df1e5ceaa5445ffeb4f11f Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Tue, 14 Jul 2026 18:57:26 +0800 Subject: [PATCH 21/44] =?UTF-8?q?feat(product):=20=E8=81=9A=E5=90=88?= =?UTF-8?q?=E5=88=86=E7=B1=BB=E5=95=86=E5=93=81=E6=9C=80=E4=BD=8E=E4=BB=B7?= =?UTF-8?q?=E4=B8=8E=E9=94=80=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + internal/repository/product_repository.go | 137 +++++----------------- internal/server/product_server.go | 31 ++--- 3 files changed, 44 insertions(+), 126 deletions(-) diff --git a/README.md b/README.md index 3a05c0b..946c47e 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `total` | `int64` | 分类/分组下商品总数 | | `total_pages` | `int32` | 总页数 | +`products[]` 返回商品摘要以及全部未删除 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。 + `products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。 ### `ListCategoryTree` diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 3fcfd67..bef4b2a 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -90,21 +90,15 @@ type InventoryRecord struct { // CategoryProductRecord is the product summary returned by category product lists. type CategoryProductRecord struct { - ID string - SPUNo string - Title string - Status productv1.ProductStatus - ImageIDs []string - CreatedAt time.Time - UpdatedAt time.Time -} - -// CategoryProductSKURecord is the SKU summary returned by category product lists. -type CategoryProductSKURecord struct { - ID string - ProductID string - AvailableQuantity int32 - Price int64 + ID string + SPUNo string + Title string + Status productv1.ProductStatus + ImageIDs []string + Price int64 + SoldQuantity int64 + CreatedAt time.Time + UpdatedAt time.Time } // CategoryRecord is the persistence model for product.product_category. @@ -489,10 +483,10 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* } // ListCategoryProducts loads paginated product summaries for a category ID. -func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, map[string][]CategoryProductSKURecord, int64, error) { +func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { parsedCategoryID, err := parseID(categoryID, "category id") if err != nil { - return nil, nil, 0, err + return nil, 0, err } if page < 1 { @@ -510,10 +504,10 @@ JOIN product.product_category_bindings b ON b.product_id = p.id WHERE b.category_id = $1 AND p.deleted_at IS NULL `, parsedCategoryID).Scan(&total); err != nil { - return nil, nil, 0, fmt.Errorf("count category products: %w", err) + return nil, 0, fmt.Errorf("count category products: %w", err) } if total == 0 { - return []*CategoryProductRecord{}, map[string][]CategoryProductSKURecord{}, 0, nil + return []*CategoryProductRecord{}, 0, nil } offset := int64(page-1) * int64(pageSize) @@ -524,16 +518,26 @@ SELECT p.updated_at, p.id, p.spu_no, p.status, - COALESCE(to_json(p.image_ids)::text, '[]') + COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(sku_summary.price, 0), + COALESCE(sku_summary.sold_quantity, 0) FROM product.products p JOIN product.product_category_bindings b ON b.product_id = p.id +LEFT JOIN LATERAL ( + SELECT MIN(pi.price) AS price, + SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity + FROM product.product_items pi + LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL +) sku_summary ON TRUE WHERE b.category_id = $1 AND p.deleted_at IS NULL ORDER BY p.created_at DESC, p.id DESC LIMIT $2 OFFSET $3 `, parsedCategoryID, pageSize, offset) if err != nil { - return nil, nil, 0, fmt.Errorf("query category products: %w", err) + return nil, 0, fmt.Errorf("query category products: %w", err) } defer rows.Close() @@ -541,28 +545,14 @@ LIMIT $2 OFFSET $3 for rows.Next() { product, err := scanCategoryProduct(rows) if err != nil { - return nil, nil, 0, err + return nil, 0, err } products = append(products, product) } if err := rows.Err(); err != nil { - return nil, nil, 0, fmt.Errorf("iterate category products: %w", err) + return nil, 0, fmt.Errorf("iterate category products: %w", err) } - if len(products) == 0 { - return products, map[string][]CategoryProductSKURecord{}, total, nil - } - - foundIDs := make([]string, 0, len(products)) - for _, product := range products { - foundIDs = append(foundIDs, product.ID) - } - - skuMap, err := r.loadCategoryProductSKUsByProductIDs(ctx, foundIDs) - if err != nil { - return nil, nil, 0, err - } - - return products, skuMap, total, nil + return products, total, nil } // ListCategoryTreeNodes loads product category nodes for storefront category trees. @@ -1034,55 +1024,6 @@ ORDER BY pi.created_at ASC return result, nil } -func (r *ProductRepository) loadCategoryProductSKUsByProductIDs(ctx context.Context, productIDs []string) (map[string][]CategoryProductSKURecord, error) { - result := make(map[string][]CategoryProductSKURecord, len(productIDs)) - if len(productIDs) == 0 { - return result, nil - } - - placeholders := make([]string, len(productIDs)) - args := make([]any, len(productIDs)) - for i, id := range productIDs { - parsed, err := parseID(id, "product id") - if err != nil { - return nil, err - } - placeholders[i] = fmt.Sprintf("$%d", i+1) - args[i] = parsed - } - - query := fmt.Sprintf(` -SELECT pi.id, - pi.product_id, - COALESCE(inv.available_quantity, 0), - pi.price -FROM product.product_items pi -LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id -WHERE pi.product_id IN (%s) - AND pi.deleted_at IS NULL -ORDER BY pi.created_at ASC -`, strings.Join(placeholders, ", ")) - - rows, err := r.db.QueryContext(ctx, query, args...) - if err != nil { - return nil, fmt.Errorf("query category product skus: %w", err) - } - defer rows.Close() - - for rows.Next() { - sku, err := scanCategoryProductSKU(rows) - if err != nil { - return nil, err - } - result[sku.ProductID] = append(result[sku.ProductID], *sku) - } - if err := rows.Err(); err != nil { - return nil, fmt.Errorf("iterate category product skus: %w", err) - } - - return result, nil -} - type rowScanner interface { Scan(dest ...any) error } @@ -1102,6 +1043,8 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { &rec.SPUNo, &status, &imageIDsJSON, + &rec.Price, + &rec.SoldQuantity, ); err != nil { return nil, fmt.Errorf("scan category product: %w", err) } @@ -1116,26 +1059,6 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { return &rec, nil } -func scanCategoryProductSKU(scanner rowScanner) (*CategoryProductSKURecord, error) { - var ( - rec CategoryProductSKURecord - id int64 - productID int64 - ) - if err := scanner.Scan( - &id, - &productID, - &rec.AvailableQuantity, - &rec.Price, - ); err != nil { - return nil, fmt.Errorf("scan category product sku: %w", err) - } - - rec.ID = formatID(id) - rec.ProductID = formatID(productID) - return &rec, nil -} - func scanProduct(scanner rowScanner) (*ProductRecord, error) { var ( rec ProductRecord diff --git a/internal/server/product_server.go b/internal/server/product_server.go index b0756bd..f218816 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -177,7 +177,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 )) defer dbSpan.End() - products, skuMap, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize) + products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -189,7 +189,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) for _, product := range products { - protoProducts = append(protoProducts, toProtoCategoryProduct(product, skuMap[product.ID])) + protoProducts = append(protoProducts, toProtoCategoryProduct(product)) } return &productv1.ListCategoryProductsResponse{ @@ -761,27 +761,20 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco } } -func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []repository.CategoryProductSKURecord) *productv1.CategoryProduct { +func toProtoCategoryProduct(product *repository.CategoryProductRecord) *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: timeToMillisString(product.UpdatedAt), - CreatedAt: timeToMillisString(product.CreatedAt), - Title: product.Title, - ProductId: product.ID, - SpuNo: product.SPUNo, - Status: product.Status, - ImageIds: product.ImageIDs, - Skus: protoSKUs, + UpdatedAt: timeToMillisString(product.UpdatedAt), + CreatedAt: timeToMillisString(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Price: product.Price, + SoldQuantity: product.SoldQuantity, } } From 68d39e75f8d4075353f5581c7fffcceb6d77649c Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Thu, 16 Jul 2026 11:38:50 +0800 Subject: [PATCH 22/44] feat(product): migrate category images to image_ids array --- internal/repository/product_repository.go | 97 +++++++++++++--------- internal/server/category_image_ids_test.go | 31 +++++++ internal/server/product_server.go | 65 ++++++++------- scripts/sql/migrate-category-image-ids.sql | 35 ++++++++ scripts/sql/recreate-product-tables.sql | 4 +- 5 files changed, 161 insertions(+), 71 deletions(-) create mode 100644 internal/server/category_image_ids_test.go create mode 100644 scripts/sql/migrate-category-image-ids.sql diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index bef4b2a..71eeec9 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -103,14 +103,14 @@ type CategoryProductRecord struct { // CategoryRecord is the persistence model for product.product_category. type CategoryRecord struct { - ID string - NodeType int32 - Name string - ParentID string - Level int32 - ImageJSON string - SortNum int32 - Status int32 + ID string + NodeType int32 + Name string + ParentID string + Level int32 + ImageIDs []string + SortNum int32 + Status int32 } // ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. @@ -132,6 +132,36 @@ ALTER TABLE product.products ALTER TABLE product.product_category_bindings ALTER COLUMN id DROP DEFAULT; +ALTER TABLE product.product_category + ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = 'product' + AND table_name = 'product_category' + AND column_name = 'image_json' + ) THEN + EXECUTE $migration$ + UPDATE product.product_category + SET image_ids = CASE + WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE( + (SELECT array_agg(image_id) + FROM jsonb_array_elements_text(image_json) AS image_id), + '{}'::VARCHAR[] + ) + ELSE '{}'::VARCHAR[] + END + WHERE image_json IS NOT NULL + $migration$; + END IF; +END $$; + +ALTER TABLE product.product_category + DROP COLUMN IF EXISTS image_json; + CREATE TABLE IF NOT EXISTS product.product_items ( id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, @@ -563,7 +593,7 @@ SELECT id, name, parent_id, level, - image_json, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status FROM product.product_category @@ -599,7 +629,7 @@ SELECT id, name, parent_id, level, - image_json, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status FROM product.product_category @@ -927,11 +957,6 @@ func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord 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, @@ -939,20 +964,20 @@ INSERT INTO product.product_category ( name, parent_id, level, - image_json, + image_ids, sort_num, status ) -VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, node_type, name, parent_id, level, - image_json, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status -`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), imageJSON, category.SortNum, int16(category.Status)) +`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status)) createdCategory, err := scanCategory(row) if err != nil { @@ -1251,16 +1276,16 @@ func scanInventory(scanner rowScanner) (*InventoryRecord, error) { func scanCategory(scanner rowScanner) (*CategoryRecord, error) { var ( - rec CategoryRecord - id int64 - parentID sql.NullInt64 - imageJSON []byte - nodeType int16 - level int16 - status int16 + rec CategoryRecord + id int64 + parentID sql.NullInt64 + imageIDsJSON []byte + nodeType int16 + level int16 + status int16 ) if err := scanner.Scan( - &id, &nodeType, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, + &id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, ); err != nil { return nil, fmt.Errorf("scan category: %w", err) } @@ -1271,10 +1296,11 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { rec.ParentID = formatID(parentID.Int64) } rec.Level = int32(level) - rec.ImageJSON = string(imageJSON) - if rec.ImageJSON == "" { - rec.ImageJSON = "[]" + imageIDs, err := parseStringArrayJSON(string(imageIDsJSON)) + if err != nil { + return nil, fmt.Errorf("unmarshal category image_ids: %w", err) } + rec.ImageIDs = imageIDs rec.Status = int32(status) return &rec, nil } @@ -1289,17 +1315,6 @@ 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/category_image_ids_test.go b/internal/server/category_image_ids_test.go new file mode 100644 index 0000000..e148ee9 --- /dev/null +++ b/internal/server/category_image_ids_test.go @@ -0,0 +1,31 @@ +package server + +import ( + "testing" + + "google.golang.org/protobuf/encoding/protojson" + + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" +) + +func TestCategoryImageIDsRoundTripThroughExistingProtoField(t *testing.T) { + imageIDs, err := normalizeNodeImageIDs(`[" image-1 ", "image-1", "image-2"]`) + if err != nil { + t.Fatalf("normalizeNodeImageIDs: %v", err) + } + if len(imageIDs) != 2 || imageIDs[0] != "image-1" || imageIDs[1] != "image-2" { + t.Fatalf("image ids = %#v", imageIDs) + } + + node := toProtoCategoryNode(&repository.CategoryRecord{ImageIDs: imageIDs}) + if got := node.GetImageJson(); got != `["image-1","image-2"]` { + t.Fatalf("image_json = %q", got) + } + if _, err := protojson.Marshal(node); err != nil { + t.Fatalf("marshal category node: %v", err) + } + + if _, err := normalizeNodeImageIDs(`{"image_id":"image-1"}`); err == nil { + t.Fatal("expected non-array image_json to be rejected") + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index f218816..6d31926 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -350,7 +350,7 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re if err != nil { return repository.CategoryRecord{}, nil, err } - imageJSON, err := normalizeNodeImageJSON(req.GetImageJson()) + imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) if err != nil { return repository.CategoryRecord{}, nil, err } @@ -360,12 +360,12 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re } parent := repository.CategoryRecord{ - NodeType: categoryNodeType, - Name: name, - Level: 1, - ImageJSON: imageJSON, - SortNum: req.GetSortNum(), - Status: statusValue, + NodeType: categoryNodeType, + Name: name, + Level: 1, + ImageIDs: imageIDs, + SortNum: req.GetSortNum(), + Status: statusValue, } children := make([]repository.CategoryRecord, 0, len(req.GetChildren())) @@ -383,7 +383,7 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re } childNames[childName] = struct{}{} - childImageJSON, err := normalizeNodeImageJSON(child.GetImageJson()) + childImageIDs, err := normalizeNodeImageIDs(child.GetImageJson()) if err != nil { return repository.CategoryRecord{}, nil, err } @@ -393,12 +393,12 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re } children = append(children, repository.CategoryRecord{ - NodeType: categoryNodeType, - Name: childName, - Level: 2, - ImageJSON: childImageJSON, - SortNum: child.GetSortNum(), - Status: childStatus, + NodeType: categoryNodeType, + Name: childName, + Level: 2, + ImageIDs: childImageIDs, + SortNum: child.GetSortNum(), + Status: childStatus, }) } @@ -410,7 +410,7 @@ func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.Categ if err != nil { return repository.CategoryRecord{}, err } - imageJSON, err := normalizeNodeImageJSON(req.GetImageJson()) + imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) if err != nil { return repository.CategoryRecord{}, err } @@ -420,12 +420,12 @@ func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.Categ } return repository.CategoryRecord{ - NodeType: groupNodeType, - Name: name, - Level: 1, - ImageJSON: imageJSON, - SortNum: req.GetSortNum(), - Status: statusValue, + NodeType: groupNodeType, + Name: name, + Level: 1, + ImageIDs: imageIDs, + SortNum: req.GetSortNum(), + Status: statusValue, }, nil } @@ -440,15 +440,16 @@ func normalizeNodeName(raw, field string) (string, error) { return name, nil } -func normalizeNodeImageJSON(raw string) (string, error) { +func normalizeNodeImageIDs(raw string) ([]string, error) { raw = strings.TrimSpace(raw) if raw == "" { - return "[]", nil + return []string{}, nil } - if !json.Valid([]byte(raw)) { - return "", errors.New("image_json must be valid json") + var imageIDs []string + if err := json.Unmarshal([]byte(raw), &imageIDs); err != nil { + return nil, errors.New("image_json must be a json string array") } - return raw, nil + return normalizeStringList(imageIDs), nil } func normalizeNodeStatus(statusValue *int32) (int32, error) { @@ -839,7 +840,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor Name: category.Name, ParentId: category.ParentID, Level: category.Level, - ImageJson: category.ImageJSON, + ImageJson: categoryImageIDsJSON(category.ImageIDs), SortNum: category.SortNum, Status: category.Status, Children: []*productv1.CategoryNode{}, @@ -856,8 +857,16 @@ func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode { Name: group.Name, ParentId: group.ParentID, Level: group.Level, - ImageJson: group.ImageJSON, + ImageJson: categoryImageIDsJSON(group.ImageIDs), SortNum: group.SortNum, Status: group.Status, } } + +func categoryImageIDsJSON(imageIDs []string) string { + encoded, err := json.Marshal(imageIDs) + if err != nil { + return "[]" + } + return string(encoded) +} diff --git a/scripts/sql/migrate-category-image-ids.sql b/scripts/sql/migrate-category-image-ids.sql new file mode 100644 index 0000000..7285382 --- /dev/null +++ b/scripts/sql/migrate-category-image-ids.sql @@ -0,0 +1,35 @@ +-- Migrate product.product_category.image_json (JSONB) to image_ids (VARCHAR[]). +-- Safe to run multiple times. The ids-svc-product startup schema check performs +-- the same migration for service-managed deployments. + +ALTER TABLE product.product_category + ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = 'product' + AND table_name = 'product_category' + AND column_name = 'image_json' + ) THEN + EXECUTE $migration$ + UPDATE product.product_category + SET image_ids = CASE + WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE( + (SELECT array_agg(image_id) + FROM jsonb_array_elements_text(image_json) AS image_id), + '{}'::VARCHAR[] + ) + ELSE '{}'::VARCHAR[] + END + WHERE image_json IS NOT NULL + $migration$; + END IF; +END $$; + +ALTER TABLE product.product_category + DROP COLUMN IF EXISTS image_json; + +COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index f798124..61d462a 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -111,7 +111,7 @@ CREATE TABLE IF NOT EXISTS product.product_category ( name VARCHAR(100) NOT NULL, parent_id BIGINT REFERENCES product.product_category(id), level SMALLINT NOT NULL, - image_json JSONB NOT NULL DEFAULT '[]'::JSONB, + image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], sort_num INTEGER NOT NULL DEFAULT 0, status SMALLINT NOT NULL DEFAULT 1, CONSTRAINT chk_product_category_node_type @@ -128,7 +128,7 @@ COMMENT ON COLUMN product.product_category.node_type IS '节点类型:0 分类 COMMENT ON COLUMN product.product_category.name IS '节点展示名称'; COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3'; -COMMENT ON COLUMN product.product_category.image_json IS '图片列表,用于小程序分类入口、分组入口展示'; +COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前'; COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示'; From aa3ee1d236f43d78dca86475b916431adaca0229 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Thu, 16 Jul 2026 12:51:40 +0800 Subject: [PATCH 23/44] feat(product): implement LockInventory method to reserve stock for pending orders --- internal/repository/product_repository.go | 52 ++++++++++++++++ internal/server/product_server.go | 73 ++++++++++++++++++----- 2 files changed, 111 insertions(+), 14 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 3fcfd67..184b871 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -21,6 +21,9 @@ var ErrProductNotFound = errors.New("product not found") // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") +// ErrInsufficientStock is returned when available - locked is less than the requested quantity. +var ErrInsufficientStock = errors.New("insufficient stock") + // ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number. var ErrDuplicateSPUNo = errors.New("spu_no already exists") @@ -448,6 +451,55 @@ WHERE id = $1 return nil } +// LockInventory atomically reserves quantity when available_quantity - locked_quantity >= quantity. +func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32) (*InventoryRecord, error) { + if quantity <= 0 { + return nil, fmt.Errorf("quantity must be positive") + } + id, err := parseID(skuID, "sku id") + if err != nil { + return nil, err + } + + row := r.db.QueryRowContext(ctx, ` +UPDATE product.product_item_inventory +SET locked_quantity = locked_quantity + $2, + version = version + 1, + updated_at = NOW() +WHERE sku_id = $1 + AND available_quantity - locked_quantity >= $2 +RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at +`, id, quantity) + inventory, err := scanInventory(row) + if errors.Is(err, sql.ErrNoRows) { + exists, existsErr := r.skuInventoryExists(ctx, id) + if existsErr != nil { + return nil, existsErr + } + if !exists { + return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrSKUNotFound) + } + return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrInsufficientStock) + } + if err != nil { + return nil, fmt.Errorf("lock inventory %s: %w", skuID, err) + } + return inventory, nil +} + +func (r *ProductRepository) skuInventoryExists(ctx context.Context, skuID int64) (bool, error) { + var exists bool + err := r.db.QueryRowContext(ctx, ` +SELECT EXISTS( + SELECT 1 FROM product.product_item_inventory WHERE sku_id = $1 +) +`, skuID).Scan(&exists) + if err != nil { + return false, fmt.Errorf("check inventory exists %s: %w", formatID(skuID), err) + } + return exists, nil +} + // DeleteSKU soft-deletes a SKU row. func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error { id, err := parseID(skuID, "sku id") diff --git a/internal/server/product_server.go b/internal/server/product_server.go index b0756bd..5fb1d93 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -334,6 +334,47 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup }, nil } +// LockInventory reserves sellable stock for a pending order. +func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) { + if req == nil || req.GetSkuId() == "" { + return nil, status.Error(codes.InvalidArgument, "sku_id is required") + } + if req.GetQuantity() <= 0 { + return nil, status.Error(codes.InvalidArgument, "quantity must be positive") + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.lock_inventory", trace.WithAttributes( + attribute.String("sku.id", req.GetSkuId()), + attribute.Int("inventory.quantity", int(req.GetQuantity())), + attribute.String("order.id", req.GetOrderId()), + )) + defer dbSpan.End() + + inventory, err := s.repo.LockInventory(dbCtx, req.GetSkuId(), req.GetQuantity()) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrSKUNotFound): + return nil, status.Error(codes.NotFound, "sku inventory not found") + case errors.Is(err, repository.ErrInsufficientStock): + return nil, status.Error(codes.FailedPrecondition, "insufficient stock") + default: + s.observer.Logger(ctx).Error("lock inventory failed", + zap.String("sku_id", req.GetSkuId()), + zap.Int32("quantity", req.GetQuantity()), + zap.String("order_id", req.GetOrderId()), + zap.Error(err), + ) + return nil, status.Errorf(codes.Internal, "lock inventory: %v", err) + } + } + + return &productv1.LockInventoryResponse{ + Inventory: toProtoInventory(inventory), + }, nil +} + func totalPages(total int64, pageSize int32) int32 { if total <= 0 || pageSize <= 0 { return 0 @@ -765,23 +806,27 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord, skus []re if product == nil { return nil } - protoSKUs := make([]*productv1.CategoryProductSKU, 0, len(skus)) + var ( + minPrice int64 + soldQuantity int64 + hasPrice bool + ) for _, sku := range skus { - protoSKUs = append(protoSKUs, &productv1.CategoryProductSKU{ - SkuId: sku.ID, - AvailableQuantity: sku.AvailableQuantity, - Price: sku.Price, - }) + if !hasPrice || sku.Price < minPrice { + minPrice = sku.Price + hasPrice = true + } } return &productv1.CategoryProduct{ - UpdatedAt: timeToMillisString(product.UpdatedAt), - CreatedAt: timeToMillisString(product.CreatedAt), - Title: product.Title, - ProductId: product.ID, - SpuNo: product.SPUNo, - Status: product.Status, - ImageIds: product.ImageIDs, - Skus: protoSKUs, + UpdatedAt: timeToMillisString(product.UpdatedAt), + CreatedAt: timeToMillisString(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Price: minPrice, + SoldQuantity: soldQuantity, } } From 787eda9f3e6ebf4ab4cea8bffdf6fe4566d66090 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Mon, 20 Jul 2026 14:44:38 +0800 Subject: [PATCH 24/44] =?UTF-8?q?feat(product):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E5=B0=86=E5=95=86=E5=93=81=E5=8A=A0=E5=85=A5?= =?UTF-8?q?=E5=88=86=E7=B1=BB=E6=88=96=E5=88=86=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/repository/product_repository.go | 106 ++++++++++++++++++++++ internal/server/product_server.go | 76 +++++++++++++++- 2 files changed, 180 insertions(+), 2 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 5d9d8e5..05f8e96 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -18,6 +18,9 @@ import ( // ErrProductNotFound is returned when a product does not exist. var ErrProductNotFound = errors.New("product not found") +// ErrCategoryNodeNotFound is returned when a category or product group node does not exist. +var ErrCategoryNodeNotFound = errors.New("category or group node not found") + // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") @@ -319,6 +322,109 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat return createdCategory, nil } +// AddProductsToGroup binds every product to the requested category or product group in one transaction. +// Existing bindings are retained and duplicate bindings are ignored. +func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string) error { + if len(productIDs) == 0 { + return errors.New("product_ids is required") + } + if len(bindingIDs) != len(productIDs) { + return errors.New("binding ids must match product ids") + } + + parsedGroupID, err := parseID(groupID, "group_id") + if err != nil { + return err + } + parsedProductIDs := make([]int64, len(productIDs)) + parsedBindingIDs := make([]int64, len(bindingIDs)) + for i := range productIDs { + parsedProductIDs[i], err = parseID(productIDs[i], "product_id") + if err != nil { + return err + } + parsedBindingIDs[i], err = parseID(bindingIDs[i], "category binding id") + if err != nil { + return err + } + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin add products to group: %w", err) + } + defer tx.Rollback() + + err = tx.QueryRowContext(ctx, ` +SELECT id +FROM product.product_category +WHERE id = $1 +`, parsedGroupID).Scan(&parsedGroupID) + if errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID) + } + if err != nil { + return fmt.Errorf("query category or group node %s: %w", groupID, err) + } + + productPlaceholders := make([]string, len(parsedProductIDs)) + productArgs := make([]any, len(parsedProductIDs)) + for i, productID := range parsedProductIDs { + productPlaceholders[i] = fmt.Sprintf("$%d", i+1) + productArgs[i] = productID + } + rows, err := tx.QueryContext(ctx, fmt.Sprintf(` +SELECT id +FROM product.products +WHERE deleted_at IS NULL + AND id IN (%s) +`, strings.Join(productPlaceholders, ", ")), productArgs...) + if err != nil { + return fmt.Errorf("query products for category or group binding: %w", err) + } + + foundProducts := make(map[int64]struct{}, len(parsedProductIDs)) + for rows.Next() { + var productID int64 + if err := rows.Scan(&productID); err != nil { + return fmt.Errorf("scan product for category or group binding: %w", err) + } + foundProducts[productID] = struct{}{} + } + if err := rows.Err(); err != nil { + return fmt.Errorf("iterate products for category or group binding: %w", err) + } + if err := rows.Close(); err != nil { + return fmt.Errorf("close products for category or group binding: %w", err) + } + for i, productID := range parsedProductIDs { + if _, ok := foundProducts[productID]; !ok { + return fmt.Errorf("%w: %s", ErrProductNotFound, productIDs[i]) + } + } + + valuePlaceholders := make([]string, len(parsedProductIDs)) + args := make([]any, 0, len(parsedProductIDs)*3) + for i, productID := range parsedProductIDs { + base := i * 3 + valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3) + args = append(args, parsedBindingIDs[i], productID, parsedGroupID) + } + _, err = tx.ExecContext(ctx, fmt.Sprintf(` +INSERT INTO product.product_category_bindings (id, product_id, category_id) +VALUES %s +ON CONFLICT (product_id, category_id) DO NOTHING +`, strings.Join(valuePlaceholders, ", ")), args...) + if err != nil { + return fmt.Errorf("insert product category or group bindings: %w", err) + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit add products to group: %w", err) + } + return nil +} + // UpdateProduct updates mutable SPU fields. func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error { attrs, err := json.Marshal(product.Attrs) diff --git a/internal/server/product_server.go b/internal/server/product_server.go index fcabc46..ae00a92 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -33,8 +33,9 @@ const ( categoryNodeType = int32(0) groupNodeType = int32(1) - defaultNodeStatus = int32(1) - maxNodeNameLength = 100 + defaultNodeStatus = int32(1) + maxNodeNameLength = 100 + maxProductsPerGroupRequest = 100 ) // ProductServer implements productv1.ProductServiceServer. @@ -334,6 +335,50 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup }, nil } +// AddProductsToGroup adds one or more products to a category or product group. +func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.AddProductsToGroupRequest) (*productv1.AddProductsToGroupResponse, 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") + } + + groupID := strings.TrimSpace(req.GetGroupId()) + if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + productIDs, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + bindingIDs := make([]string, len(productIDs)) + for i := range productIDs { + // Each binding row receives its own Snowflake ID. + bindingIDs[i] = s.idgen.NextString() + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.add_products", trace.WithAttributes( + attribute.String("group.id", groupID), + attribute.Int("group.product_count", len(productIDs)), + )) + defer dbSpan.End() + + if err := s.repo.AddProductsToGroup(dbCtx, groupID, bindingIDs, productIDs); err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("add products to group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err)) + switch { + case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrProductNotFound): + return nil, status.Error(codes.NotFound, err.Error()) + default: + return nil, status.Errorf(codes.Internal, "add products to group: %v", err) + } + } + + return &productv1.AddProductsToGroupResponse{Success: true}, nil +} + // LockInventory reserves sellable stock for a pending order. func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) { if req == nil || req.GetSkuId() == "" { @@ -713,6 +758,33 @@ func normalizeStringList(values []string) []string { return out } +func normalizeGroupProductIDs(values []string) ([]string, error) { + productIDs := normalizeStringList(values) + if len(productIDs) == 0 { + return nil, errors.New("product_ids is required") + } + if len(productIDs) > maxProductsPerGroupRequest { + return nil, fmt.Errorf("product_ids must contain at most %d items", maxProductsPerGroupRequest) + } + for _, productID := range productIDs { + if err := validatePositiveSnowflakeID(productID, "product_id"); err != nil { + return nil, err + } + } + return productIDs, nil +} + +func validatePositiveSnowflakeID(raw, field string) error { + if strings.TrimSpace(raw) == "" { + return fmt.Errorf("%s is required", field) + } + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return fmt.Errorf("%s must be a positive snowflake id", field) + } + return nil +} + func defaultInt32(value, fallback int32) int32 { if value == 0 { return fallback From cccbce7bc592e9545868848c0ed6ce7929620996 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Mon, 20 Jul 2026 15:13:59 +0800 Subject: [PATCH 25/44] =?UTF-8?q?feat(product):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E7=A7=BB=E9=99=A4=E5=88=86=E7=B1=BB=E6=88=96?= =?UTF-8?q?=E5=88=86=E7=BB=84=E4=B8=AD=E7=9A=84=E5=95=86=E5=93=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/repository/product_repository.go | 59 +++++++++++++++++++++++ internal/server/product_server.go | 34 +++++++++++++ 2 files changed, 93 insertions(+) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 05f8e96..2f8bad2 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -425,6 +425,65 @@ ON CONFLICT (product_id, category_id) DO NOTHING return nil } +// RemoveProductsFromGroup removes product bindings from the requested category or product group in one transaction. +// Missing bindings are ignored so callers can safely retry the same request. +func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string) error { + if len(productIDs) == 0 { + return errors.New("product_ids is required") + } + + parsedGroupID, err := parseID(groupID, "group_id") + if err != nil { + return err + } + parsedProductIDs := make([]int64, len(productIDs)) + for i := range productIDs { + parsedProductIDs[i], err = parseID(productIDs[i], "product_id") + if err != nil { + return err + } + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin remove products from group: %w", err) + } + defer tx.Rollback() + + err = tx.QueryRowContext(ctx, ` +SELECT id +FROM product.product_category +WHERE id = $1 +`, parsedGroupID).Scan(&parsedGroupID) + if errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID) + } + if err != nil { + return fmt.Errorf("query category or group node %s: %w", groupID, err) + } + + placeholders := make([]string, len(parsedProductIDs)) + args := make([]any, 0, len(parsedProductIDs)+1) + args = append(args, parsedGroupID) + for i, productID := range parsedProductIDs { + placeholders[i] = fmt.Sprintf("$%d", i+2) + args = append(args, productID) + } + _, err = tx.ExecContext(ctx, fmt.Sprintf(` +DELETE FROM product.product_category_bindings +WHERE category_id = $1 + AND product_id IN (%s) +`, strings.Join(placeholders, ", ")), args...) + if err != nil { + return fmt.Errorf("delete product category or group bindings: %w", err) + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit remove products from group: %w", err) + } + return nil +} + // UpdateProduct updates mutable SPU fields. func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRecord) error { attrs, err := json.Marshal(product.Attrs) diff --git a/internal/server/product_server.go b/internal/server/product_server.go index ae00a92..23fda56 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -379,6 +379,40 @@ func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.A return &productv1.AddProductsToGroupResponse{Success: true}, nil } +// RemoveProductsFromGroup removes one or more products from a category or product group. +func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *productv1.RemoveProductsFromGroupRequest) (*productv1.RemoveProductsFromGroupResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + + groupID := strings.TrimSpace(req.GetGroupId()) + if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + productIDs, err := normalizeGroupProductIDs(req.GetProductIds()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.remove_products", trace.WithAttributes( + attribute.String("group.id", groupID), + attribute.Int("group.product_count", len(productIDs)), + )) + defer dbSpan.End() + + if err := s.repo.RemoveProductsFromGroup(dbCtx, groupID, productIDs); err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("remove products from group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err)) + if errors.Is(err, repository.ErrCategoryNodeNotFound) { + return nil, status.Error(codes.NotFound, err.Error()) + } + return nil, status.Errorf(codes.Internal, "remove products from group: %v", err) + } + + return &productv1.RemoveProductsFromGroupResponse{Success: true}, nil +} + // LockInventory reserves sellable stock for a pending order. func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) { if req == nil || req.GetSkuId() == "" { From 939584e32ac4ad2639b581d179582c530c239bcd Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Sat, 25 Jul 2026 13:27:13 +0800 Subject: [PATCH 26/44] chore(deps): update google.golang.org/grpc to v1.82.0 and other indirect dependencies --- go.mod | 14 +++++++------- go.sum | 28 ++++++++++++++-------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/go.mod b/go.mod index 72fadc2..63ef309 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( go.opentelemetry.io/otel/sdk v1.43.0 go.opentelemetry.io/otel/trace v1.43.0 go.uber.org/zap v1.28.0 - google.golang.org/grpc v1.81.1 + google.golang.org/grpc v1.82.0 google.golang.org/protobuf v1.36.11 llms.idsbuybuybuy.com/ecommerce/ids-proto v0.0.0-00010101000000-000000000000 ) @@ -41,10 +41,10 @@ require ( go.opentelemetry.io/proto/otlp v1.10.0 // indirect go.uber.org/multierr v1.10.0 // indirect go.yaml.in/yaml/v2 v2.4.2 // indirect - golang.org/x/net v0.52.0 // indirect - golang.org/x/sync v0.20.0 // indirect - golang.org/x/sys v0.42.0 // indirect - golang.org/x/text v0.35.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d // indirect + golang.org/x/net v0.56.0 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.40.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260720155508-bb71a54f79dc // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260720155508-bb71a54f79dc // indirect ) diff --git a/go.sum b/go.sum index fae7067..abd826b 100644 --- a/go.sum +++ b/go.sum @@ -89,22 +89,22 @@ go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= -golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= -golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= -golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= -golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= -golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA= -google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d h1:wT2n40TBqFY6wiwazVK9/iTWbsQrgk5ZfCSVFLO9LQA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= -google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= +google.golang.org/genproto/googleapis/api v0.0.0-20260720155508-bb71a54f79dc h1:fi+kqxHxmaxbnTnxOutQrJvK9ANhJIZAWkXwoTki6WM= +google.golang.org/genproto/googleapis/api v0.0.0-20260720155508-bb71a54f79dc/go.mod h1:WRrQ7/7N19PypuT0fxLOL5Lq0waoiRri4FbtHDEKrGE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260720155508-bb71a54f79dc h1:3TtNq/QbJNrSY1nVdjcikfBw6ujnaNbdrd88wNr1OW4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260720155508-bb71a54f79dc/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU= +google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 6b55143fc737f18f5d168ef114bcfb1cc2b49fcc Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Mon, 3 Aug 2026 10:49:32 +0800 Subject: [PATCH 27/44] feat(logging): implement custom logger with ISO8601 timestamp encoding --- cmd/main.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/cmd/main.go b/cmd/main.go index 69499ab..b97fb8a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -12,6 +12,7 @@ import ( _ "github.com/jackc/pgx/v5/stdlib" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.uber.org/zap" + "go.uber.org/zap/zapcore" "google.golang.org/grpc" "google.golang.org/grpc/health" healthpb "google.golang.org/grpc/health/grpc_health_v1" @@ -27,7 +28,7 @@ import ( ) func main() { - logger, err := zap.NewProduction() + logger, err := newLogger() if err != nil { panic(err) } @@ -124,3 +125,9 @@ func main() { logger.Error("shutdown metrics server failed", zap.Error(err)) } } + +func newLogger() (*zap.Logger, error) { + cfg := zap.NewProductionConfig() + cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + return cfg.Build() +} From 077ac904384360634fcb4c7ca0b06b194803bb11 Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Wed, 5 Aug 2026 17:04:59 +0800 Subject: [PATCH 28/44] feat(product): add paginated admin product listing --- README.md | 21 ++++++- internal/observability/observability.go | 14 +++++ internal/repository/product_repository.go | 67 ++++++++++++++++++++++- internal/server/product_server.go | 59 ++++++++++++++++---- scripts/sql/recreate-product-tables.sql | 4 ++ 5 files changed, 150 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 946c47e..e1f3714 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 |-----|------|-----------| | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | +| `ListProducts` | 分页返回全部未软删除商品列表 | Admin API | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | | `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF | @@ -17,12 +18,13 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 ## 接口清单 -当前商品服务对外暴露 3 个接口,REST 路径由 `google.api.http` 注解提供给 APISIX gRPC-Transcode 使用。 +商品服务对外接口的 REST 路径由 `google.api.http` 注解提供给 APISIX gRPC-Transcode 使用。 | RPC | REST | 请求 | 响应 | 说明 | |---|---|---|---|---| | `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 | | `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 | +| `ListProducts` | `GET /v1/products?page=1&page_size=20` | `ListProductsRequest` | `ListProductsResponse` | 分页查询全部未软删除商品 | | `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` 的商品分类,并按父子层级返回树 | @@ -103,6 +105,15 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。时间字段统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。 +### `ListProducts` + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 | +| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` | + +返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未删除 SKU 的最低售价(分),`sold_quantity` 为未删除 SKU 的累计销量。 + ### `ListCategoryProducts` | 字段 | 类型 | 必填 | 说明 | @@ -214,8 +225,8 @@ 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_category_tree_lists_total` | 统计商品创建成功数、分类商品查询成功数和分类树查询成功数 | -| 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、分类商品查询补充业务 span | +| 商品业务指标 | `ids_product_products_created_total`, `ids_product_product_lists_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` | ### 构建与运行 @@ -245,6 +256,10 @@ grpcurl -plaintext -d '{"spu_no":"","title":"商品标题","selling_poin # 分页查询分类商品 grpcurl -plaintext -d '{"category_id":"","page":1,"page_size":20}' \ localhost:50052 ids.product.v1.ProductService/ListCategoryProducts + +# 分页查询全部未软删除商品 +grpcurl -plaintext -d '{"page":1,"page_size":20}' \ + localhost:50052 ids.product.v1.ProductService/ListProducts ``` ## 数据模型 diff --git a/internal/observability/observability.go b/internal/observability/observability.go index 52d6ba9..c4bebb5 100644 --- a/internal/observability/observability.go +++ b/internal/observability/observability.go @@ -65,6 +65,15 @@ var ( }, ) + productListsTotal = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "product_lists_total", + Help: "Total number of successful all-product list queries.", + }, + ) + categoryTreeListsTotal = promauto.NewCounter( prometheus.CounterOpts{ Namespace: "ids", @@ -209,6 +218,11 @@ func IncCategoryProductLists() { categoryProductListsTotal.Inc() } +// IncProductLists records a successful all-product list query. +func IncProductLists() { + productListsTotal.Inc() +} + // IncCategoryTreeLists records a successful category tree query. func IncCategoryTreeLists() { categoryTreeListsTotal.Inc() diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 2f8bad2..004b15c 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -94,7 +94,7 @@ type InventoryRecord struct { UpdatedAt time.Time } -// CategoryProductRecord is the product summary returned by category product lists. +// CategoryProductRecord is the product summary returned by product list endpoints. type CategoryProductRecord struct { ID string SPUNo string @@ -202,6 +202,7 @@ ALTER TABLE product.product_items CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL; ` if _, err := r.db.ExecContext(ctx, ddl); err != nil { return fmt.Errorf("ensure product tables: %w", err) @@ -729,6 +730,70 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* return product, skus[productID], nil } +// ListProducts loads paginated summaries for all non-deleted products. +func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + + var total int64 + if err := r.db.QueryRowContext(ctx, ` +SELECT COUNT(*) +FROM product.products +WHERE deleted_at IS NULL +`).Scan(&total); err != nil { + return nil, 0, fmt.Errorf("count products: %w", err) + } + if total == 0 { + return []*CategoryProductRecord{}, 0, nil + } + + offset := int64(page-1) * int64(pageSize) + rows, err := r.db.QueryContext(ctx, ` +SELECT p.updated_at, + p.created_at, + p.title, + p.id, + p.spu_no, + p.status, + COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(sku_summary.price, 0), + COALESCE(sku_summary.sold_quantity, 0) +FROM product.products p +LEFT JOIN LATERAL ( + SELECT MIN(pi.price) AS price, + SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity + FROM product.product_items pi + LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL +) sku_summary ON TRUE +WHERE p.deleted_at IS NULL +ORDER BY p.created_at DESC, p.id DESC +LIMIT $1 OFFSET $2 +`, pageSize, offset) + if err != nil { + return nil, 0, fmt.Errorf("query products: %w", err) + } + defer rows.Close() + + products := make([]*CategoryProductRecord, 0, pageSize) + for rows.Next() { + product, err := scanCategoryProduct(rows) + if err != nil { + return nil, 0, err + } + products = append(products, product) + } + if err := rows.Err(); err != nil { + return nil, 0, fmt.Errorf("iterate products: %w", err) + } + return products, total, nil +} + // ListCategoryProducts loads paginated product summaries for a category ID. func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { parsedCategoryID, err := parseID(categoryID, "category id") diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 23fda56..d9c1d19 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -149,6 +149,40 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc }, nil } +// ListProducts returns a paginated list of all non-deleted products. +func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) { + page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list", trace.WithAttributes( + attribute.Int("page", int(page)), + attribute.Int("page_size", int(pageSize)), + )) + defer dbSpan.End() + + products, total, err := s.repo.ListProducts(dbCtx, page, pageSize) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("list products failed", zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "list products: %v", err) + } + dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) + observability.IncProductLists() + + protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) + for _, product := range products { + protoProducts = append(protoProducts, toProtoCategoryProduct(product)) + } + + return &productv1.ListProductsResponse{ + Products: protoProducts, + Page: page, + PageSize: pageSize, + Total: total, + TotalPages: totalPages(total, pageSize), + }, nil +} + // ListCategoryProducts returns a paginated product list under a category. func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { if req == nil || req.GetCategoryId() == "" { @@ -159,17 +193,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 return nil, status.Error(codes.InvalidArgument, "category_id must be a positive snowflake id") } - page := req.GetPage() - if page <= 0 { - page = 1 - } - pageSize := req.GetPageSize() - if pageSize <= 0 { - pageSize = defaultPageSize - } - if pageSize > maxPageSize { - pageSize = maxPageSize - } + page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_by_category", trace.WithAttributes( attribute.String("category.id", req.GetCategoryId()), @@ -202,6 +226,19 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 }, nil } +func normalizedPage(page, pageSize int32) (int32, int32) { + if page <= 0 { + page = 1 + } + if pageSize <= 0 { + pageSize = defaultPageSize + } + if pageSize > maxPageSize { + pageSize = maxPageSize + } + return page, pageSize +} + // 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 diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 61d462a..01d20d5 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -101,6 +101,10 @@ CREATE INDEX IF NOT EXISTS idx_products_goods_type CREATE INDEX IF NOT EXISTS idx_products_deleted_at ON product.products (deleted_at); +CREATE INDEX IF NOT EXISTS idx_products_active_created_id + ON product.products (created_at DESC, id DESC) + WHERE deleted_at IS NULL; + CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no ON product.products (spu_no) WHERE deleted_at IS NULL; From bec6d5a69a4b6da28c019cc60e83298ab59caddf Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Thu, 6 Aug 2026 11:09:46 +0800 Subject: [PATCH 29/44] feat(product): support product lifecycle updates and archived SKU replacement --- README.md | 19 +- docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md | 288 +++++++++ internal/repository/product_repository.go | 576 +++++++++++++++++- internal/server/product_server.go | 315 +++++++++- ...migrate-product-status-and-sku-archive.sql | 54 ++ scripts/sql/recreate-product-tables.sql | 18 +- 6 files changed, 1232 insertions(+), 38 deletions(-) create mode 100644 docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md create mode 100644 scripts/sql/migrate-product-status-and-sku-archive.sql diff --git a/README.md b/README.md index e1f3714..28fb70f 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | | `ListProducts` | 分页返回全部未软删除商品列表 | Admin API | +| `UpdateProduct` | 更新 SPU 字段,并更新或替换 SKU 集合 | Admin API | +| `UpdateProductStatus` | 显式变更仓库中、上架、已售罄状态 | Admin API | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | | `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF | @@ -25,6 +27,8 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 | | `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 | | `ListProducts` | `GET /v1/products?page=1&page_size=20` | `ListProductsRequest` | `ListProductsResponse` | 分页查询全部未软删除商品 | +| `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU | +| `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 | | `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` 的商品分类,并按父子层级返回树 | @@ -53,13 +57,13 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `leaf_category_id` | 否 | 已存在的分类/分组节点 ID;传入后会写入分类绑定 | | `image_ids` | 否 | 商品图片 ID 列表 | | `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID | -| `status` | 否 | 未传时默认草稿 | +| `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`OFF_SALE` | | `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 原味`。 +`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。 最小示例: @@ -112,7 +116,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 | | `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` | -返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未删除 SKU 的最低售价(分),`sold_quantity` 为未删除 SKU 的累计销量。 +返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。 ### `ListCategoryProducts` @@ -121,6 +125,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `category_id` | `string` | 是 | 分类/分组节点 ID,对应 `product.product_category.id` | | `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 | | `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` | +| `only_visible` | `bool` | 否 | 为 `true` 时返回 `ON_SALE` 和 `OFF_SALE` 商品;小程序 BFF 固定传 `true`,Admin 不传以查看全部状态 | 分页响应字段: @@ -132,7 +137,11 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `total` | `int64` | 分类/分组下商品总数 | | `total_pages` | `int32` | 总页数 | -`products[]` 返回商品摘要以及全部未删除 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。 +`products[]` 返回商品摘要以及全部未归档 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。 + +### `UpdateProduct` 与 `UpdateProductStatus` + +完整的输入输出及状态/SKU 规则见 [`docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md`](docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md)。重点约束:更新请求必须携带 SPU、SKU 和库存的乐观锁版本;`PATCH_EXISTING` 可更新 SKU `name`;`REPLACE_ALL` 仅允许在 `INVENTORY` 或 `OFF_SALE` 状态执行,并归档而不删除旧 SKU(即使存在锁定库存)。库存耗尽仅会自动将 `ON_SALE` 转为 `OFF_SALE`,补库存不会自动上架。 `products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。 @@ -250,7 +259,7 @@ grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct # 创建商品;product_id 和 sku_id 由服务生成 -grpcurl -plaintext -d '{"spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ +grpcurl -plaintext -d '{"spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_INVENTORY","skus":[]}' \ localhost:50052 ids.product.v1.ProductService/CreateProduct # 分页查询分类商品 diff --git a/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md b/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md new file mode 100644 index 0000000..226bc89 --- /dev/null +++ b/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md @@ -0,0 +1,288 @@ +# 商品更新、状态与 SKU 归档设计 + +## 1. 目标与边界 + +本设计新增以下管理端能力: + +- 更新商品 SPU 信息和 SKU; +- 更新商品经营状态; +- SKU 规格整体替换时保留旧 SKU 与库存记录,不物理删除; +- 历史订单继续展示下单时的商品与 SKU 快照。 + +商品域只读写 PostgreSQL 的 `product` schema。历史订单展示由订单域读取 `trade.order_items` 中的快照字段,不依赖当前 SKU 是否有效。 + +## 2. 状态模型 + +### 2.1 商品状态 + +`product.products.status` 使用以下值: + +| 数据库存储值 | Proto / API 枚举 | 含义 | 小程序行为 | +|---:|---|---|---| +| `1` | `PRODUCT_STATUS_INVENTORY` | 在仓库 | 不展示、不可购买 | +| `2` | `PRODUCT_STATUS_ON_SALE` | 已上架 | 展示、可购买 | +| `3` | `PRODUCT_STATUS_OFF_SALE` | 已售罄 | 展示已售罄状态、不可购买 | + +Proto 定义: + +```proto +enum ProductStatus { + PRODUCT_STATUS_INVENTORY = 1; + PRODUCT_STATUS_ON_SALE = 2; + PRODUCT_STATUS_OFF_SALE = 3; +} +``` + +状态流转: + +```text +INVENTORY -> ON_SALE + 运营人员上架;至少存在一个可售 SKU。 + +ON_SALE -> OFF_SALE + 所有当前可售 SKU 的 available_quantity - locked_quantity <= 0 时系统自动下架, + 或由运营人员主动下架。 + +OFF_SALE -> ON_SALE + 仅由运营人员主动重新上架;补货不会自动恢复上架。 + +ON_SALE 或 OFF_SALE -> INVENTORY + 运营人员放回仓库。 +``` + +### 2.2 SKU 状态与归档 + +`product.product_items.status` 保持现有含义: + +| 值 | 含义 | +|---:|---| +| `0` | 暂停使用;管理端可见,可重新启用 | +| `1` | 启用;可参与销售 | + +为 SKU 增加: + +```sql +is_archived BOOLEAN NOT NULL DEFAULT FALSE, +archived_at TIMESTAMPTZ NULL +``` + +并添加约束: + +```sql +CHECK ( + (is_archived = FALSE AND archived_at IS NULL) + OR + (is_archived = TRUE AND archived_at IS NOT NULL) +) +``` + +| `status` | `is_archived` | 含义 | +|---:|---:|---| +| `0` | `false` | 当前 SKU 暂停销售;运营人员可见、可恢复 | +| `1` | `false` | 当前有效 SKU | +| `0` | `true` | 历史 SKU;普通管理端不展示,不可销售、不可更新 | +| `1` | `true` | 非法组合,服务端禁止 | + +`is_archived` 是 SKU 生命周期字段,不能由管理端直接写入;仅 SKU 整体替换流程可以将旧 SKU 归档。 + +## 3. 管理端接口 + +### 3.1 更新商品与 SKU + +```http +PATCH /admin/v1/products/{product_id} +Content-Type: application/json +``` + +`expected_version` 必填。未传的 SPU 字段保持原值;数组字段传空数组代表清空。 + +```json +{ + "expected_version": 12, + "title": "中秋礼盒升级版", + "selling_point": "限时优惠", + "image_ids": ["726390485721088010"], + "sku_change": { + "mode": "PATCH_EXISTING", + "items": [ + { + "sku_id": "726390485721088101", + "expected_sku_version": 3, + "expected_inventory_version": 8, + "name": "红色 M 码", + "price": 9900, + "available_quantity": 50, + "status": 1, + "image_ids": ["726390485721088011"] + } + ] + } +} +``` + +#### 可更新 SPU 字段 + +- `title`、`selling_point`; +- `brand_id`、`supplier_id`; +- `image_ids`、`detail_html`、`member_discount_enabled`、`service_guarantees`; +- `cross_border_info`; +- 运费、开售时间、商品类型相关字段。 + +不允许通过本接口更新 `spu_no`、商品 `status`、分类/分组绑定、`sold_quantity`、`locked_quantity`、`is_archived` 或 `archived_at`。 + +#### `PATCH_EXISTING` + +仅更新已有 SKU 的可变字段: + +- `price`; +- `name`; +- `available_quantity`; +- `status`; +- `image_ids`。 + +不能修改 `sku_no`、`k1/v1` 至 `k3/v3`、销量或锁定库存。`name` 可单独覆盖,不影响 SKU 编号和规格组合。`available_quantity` 是更新后的绝对数量,且不得小于 `locked_quantity`。 + +SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。 + +#### `REPLACE_ALL` + +用于 SKU 数量或规格结构变化,包括新增、移除、合并、拆分 SKU,或修改 `sku_no`、规格组合。 + +```json +{ + "expected_version": 12, + "sku_change": { + "mode": "REPLACE_ALL", + "items": [ + { + "sku_no": "SKU-RED-M", + "price": 9900, + "available_quantity": 20, + "status": 1, + "k1": "颜色", + "v1": "红色", + "k2": "尺寸", + "v2": "M", + "image_ids": ["726390485721088011"] + } + ] + } +} +``` + +即使旧 SKU 有 `locked_quantity > 0`,也允许整体替换。替换事务执行: + +1. 锁定商品与当前 SKU 记录; +2. 将旧 SKU 设为 `status = 0`、`is_archived = true`、`archived_at = NOW()`; +3. 保留旧 SKU 的可售量、锁定量与销量,保证待支付订单、取消订单、支付完成等流程可继续按旧 SKU ID 结算; +4. 新建全部目标 SKU 和库存记录; +5. 禁止为已归档 SKU 创建新的库存锁定; +6. 商品版本递增,并重新计算商品是否自动售罄。 + +仅在商品处于 `INVENTORY` 或 `OFF_SALE` 时允许 `REPLACE_ALL`;商品为 `ON_SALE` 时必须返回冲突错误,避免上架中替换规格影响购物车和下单。 + +成功响应: + +```json +{ + "product": { + "product_id": "726390485721088003", + "status": "PRODUCT_STATUS_INVENTORY", + "version": 13, + "skus": [ + { + "sku_id": "726390485721088201", + "sku_no": "SKU-RED-M", + "price": 9900, + "available_quantity": 20, + "status": 1, + "is_archived": false, + "version": 1 + } + ] + }, + "sku_change_result": { + "mode": "REPLACE_ALL", + "created_sku_ids": ["726390485721088201"], + "archived_sku_ids": ["726390485721088101"], + "updated_sku_ids": [] + } +} +``` + +### 3.2 更新商品状态 + +```http +PATCH /admin/v1/products/{product_id}/status +Content-Type: application/json +``` + +```json +{ + "status": "PRODUCT_STATUS_ON_SALE", + "expected_version": 13 +} +``` + +运营人员可以提交 `INVENTORY`、`ON_SALE`、`OFF_SALE`。无论商品是运营人员手动下架,还是因无可售库存自动切换为 `OFF_SALE`,都只能通过本接口显式重新设置为 `ON_SALE`;库存补充本身不会改变商品状态。 + +上架时必须存在至少一个启用、未归档且 `available_quantity > locked_quantity` 的 SKU。 + +```json +{ + "product_id": "726390485721088003", + "previous_status": "PRODUCT_STATUS_ON_SALE", + "status": "PRODUCT_STATUS_OFF_SALE", + "version": 14, + "updated_at": "1754388000000" +} +``` + +## 4. 所有商品接口的归档规则 + +| 接口 | 归档规则 | +|---|---| +| 创建商品 | 不接收归档字段;新 SKU 固定为 `is_archived=false`、`archived_at=null` | +| 查询商品详情 | SKU 协议增加归档字段;普通管理端和小程序默认过滤归档 SKU | +| 查询全部商品 | 仅用未归档 SKU 聚合最低价和销量 | +| 查询分类商品 | 仅用未归档 SKU 聚合最低价和销量 | +| 更新商品 | 已归档 SKU 不允许 `PATCH_EXISTING`;`REPLACE_ALL` 归档旧 SKU | +| 更新状态 | 上架校验仅统计启用、未归档且有可售量的 SKU | +| 锁库存 | 新订单仅可锁定启用且未归档 SKU | +| 订单取消、支付、库存结算 | 必须支持处理已归档 SKU 的既有订单 | + +SKU 协议需要增加 `is_archived`、`archived_at` 与版本字段。普通接口过滤已归档 SKU,因此普通运营人员不会看到历史 SKU;订单历史展示应使用订单快照。 + +## 5. 数据库迁移 + +现有商品状态迁移: + +| 旧值 | 旧含义 | 新值 | 新含义 | +|---:|---|---:|---| +| `0` | DRAFT | `1` | INVENTORY | +| `1` | ON_SALE | `2` | ON_SALE | +| `3` | OFF_SALE | `3` | OFF_SALE | +| `2` | 当前无有效语义 | `1` | INVENTORY | + +迁移后,`status` 默认值为 `1`,约束为 `status IN (1, 2, 3)`。 + +SKU 编号唯一索引只约束当前有效 SKU: + +```sql +CREATE UNIQUE INDEX uq_product_items_sku_no_active +ON product.product_items (sku_no) +WHERE sku_no IS NOT NULL + AND deleted_at IS NULL + AND is_archived = FALSE; +``` + +必须先创建新索引,再删除旧 `uq_product_items_sku_no` 索引;否则归档 SKU 仍会阻止复用原 `sku_no`。 + +## 6. 实施位置 + +- `ids-proto/proto/ids/product/v1/product.proto`:状态枚举、SKU 归档字段、版本字段、更新 RPC 与消息; +- `ids-svc-product/internal/repository/product_repository.go`:状态映射、归档字段、SKU 替换,以及仅在已上架商品无可售库存时自动下架的计算; +- `ids-svc-product/internal/server/product_server.go`:更新校验、状态流转与 gRPC 错误映射; +- `ids-svc-product` SQL 初始化、重建和正式迁移脚本:字段、约束和索引; +- `ids-admin-api/internal/handler`、`internal/service`:两个 PATCH 路由、DTO、Mapper、版本冲突映射与图片 URL 解析; +- `admin接口描述.md`:管理端接口请求、响应、归档语义、自动售罄规则与错误码。 diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 004b15c..4313658 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -27,9 +27,24 @@ var ErrSKUNotFound = errors.New("sku not found") // ErrInsufficientStock is returned when available - locked is less than the requested quantity. var ErrInsufficientStock = errors.New("insufficient stock") +// ErrProductNotOnSale is returned when a new inventory reservation targets a product that is not on sale. +var ErrProductNotOnSale = errors.New("product is not on sale") + // ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number. var ErrDuplicateSPUNo = errors.New("spu_no already exists") +// ErrProductVersionConflict indicates that a concurrent product change won the optimistic-lock race. +var ErrProductVersionConflict = errors.New("product version conflict") + +// ErrSKUVersionConflict indicates that a concurrent SKU or inventory change won the optimistic-lock race. +var ErrSKUVersionConflict = errors.New("sku version conflict") + +// ErrSKUArchived is returned when an operation attempts to modify an archived SKU. +var ErrSKUArchived = errors.New("sku is archived") + +// ErrSKUReplacementRequiresNotOnSale is returned when replacing SKUs for an on-sale product. +var ErrSKUReplacementRequiresNotOnSale = errors.New("sku replacement requires inventory or off-sale product status") + // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { ID string @@ -53,6 +68,7 @@ type ProductRecord struct { ScheduledSaleTime *time.Time LeafCategoryID string CategoryBindingID string + Version int32 DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time @@ -77,6 +93,9 @@ type SKURecord struct { K3 string V3 string Status int32 + IsArchived bool + ArchivedAt *time.Time + Version int32 DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time @@ -90,10 +109,62 @@ type InventoryRecord struct { AvailableQuantity int32 LockedQuantity int32 SoldQuantity int32 + Version int32 CreatedAt time.Time UpdatedAt time.Time } +// SKUChangeMode selects how SKU input is applied during a product update. +type SKUChangeMode int32 + +const ( + SKUChangeModePatchExisting SKUChangeMode = 1 + SKUChangeModeReplaceAll SKUChangeMode = 2 +) + +// SKUUpdate contains mutable fields for one existing current SKU. +type SKUUpdate struct { + ID string + ExpectedSKUVersion int32 + ExpectedInventoryVersion int32 + Name *string + Price *int64 + AvailableQuantity *int32 + Status *int32 + ImageIDs *[]string +} + +// SKUChange is the optional SKU operation embedded in a product update. +type SKUChange struct { + Mode SKUChangeMode + PatchItems []SKUUpdate + ReplaceItems []SKURecord +} + +// ProductUpdateInput is the atomically persisted product update payload. +type ProductUpdateInput struct { + Product ProductRecord + ExpectedVersion int32 + SKUChange *SKUChange +} + +// SKUChangeResult records the SKU IDs affected by a product update. +type SKUChangeResult struct { + Mode SKUChangeMode + CreatedSKUIds []string + ArchivedSKUIds []string + UpdatedSKUIds []string +} + +// ProductStatusUpdate contains the resulting status projection. +type ProductStatusUpdate struct { + ProductID string + PreviousStatus productv1.ProductStatus + Status productv1.ProductStatus + Version int32 + UpdatedAt time.Time +} + // CategoryProductRecord is the product summary returned by product list endpoints. type CategoryProductRecord struct { ID string @@ -177,10 +248,14 @@ CREATE TABLE IF NOT EXISTS product.product_items ( image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], attributes JSONB NOT NULL DEFAULT '{}', status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + is_archived BOOLEAN NOT NULL DEFAULT FALSE, + archived_at TIMESTAMPTZ, version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), deleted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT chk_product_items_archived + CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL)) ); CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, @@ -199,9 +274,13 @@ ALTER TABLE product.product_items ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; -CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; -CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS is_archived BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ; +CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL AND is_archived = FALSE; +CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL AND is_archived = FALSE; +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE; CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL; ` if _, err := r.db.ExecContext(ctx, ddl); err != nil { @@ -519,6 +598,379 @@ WHERE id = $1 return nil } +// UpdateProductWithSKUChange atomically persists a merged SPU update and an optional SKU operation. +func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, input ProductUpdateInput) (*SKUChangeResult, error) { + if input.ExpectedVersion < 0 { + return nil, fmt.Errorf("expected product version must be non-negative") + } + productID, err := parseID(input.Product.ID, "product id") + if err != nil { + return nil, err + } + attrs, err := productCrossBorderJSON(input.Product) + if err != nil { + return nil, err + } + brandID, err := nullableID(input.Product.BrandID, "brand_id") + if err != nil { + return nil, err + } + supplierID, err := nullableID(input.Product.SupplierID, "supplier_id") + if err != nil { + return nil, err + } + freightTemplateID, err := nullableID(input.Product.FreightTemplateID, "freight_template_id") + if err != nil { + return nil, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin update product: %w", err) + } + defer tx.Rollback() + + var currentStatus int16 + var currentVersion int32 + err = tx.QueryRowContext(ctx, ` +SELECT status, version +FROM product.products +WHERE id = $1 AND deleted_at IS NULL +FOR UPDATE +`, productID).Scan(¤tStatus, ¤tVersion) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductNotFound + } + if err != nil { + return nil, fmt.Errorf("lock product %s: %w", input.Product.ID, err) + } + if currentVersion != input.ExpectedVersion { + return nil, ErrProductVersionConflict + } + + if input.SKUChange != nil && input.SKUChange.Mode == SKUChangeModeReplaceAll && statusFromDB(currentStatus) == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE { + return nil, ErrSKUReplacementRequiresNotOnSale + } + + if _, err := tx.ExecContext(ctx, ` +UPDATE product.products +SET title = $2, + selling_point = $3, + brand_id = $4, + supplier_id = $5, + image_ids = $6, + detail_html = $7, + member_discount_enabled = $8, + goods_type = $9, + service_guarantees = $10, + cross_border = $11::jsonb, + freight_charge_type = $12, + freight_fixed_amount = $13, + freight_template_id = $14, + sale_time_type = $15, + scheduled_sale_time = $16, + version = version + 1, + updated_at = NOW() +WHERE id = $1 AND version = $17 AND deleted_at IS NULL +`, productID, input.Product.Title, input.Product.SellingPoint, brandID, supplierID, + stringSliceOrEmpty(input.Product.ImageIDs), input.Product.DetailHTML, input.Product.MemberDiscountEnabled, + int16(input.Product.GoodsType), stringSliceOrEmpty(input.Product.ServiceGuarantees), attrs, + int16(input.Product.FreightChargeType), input.Product.FreightFixedAmount, freightTemplateID, + int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, input.ExpectedVersion); err != nil { + return nil, fmt.Errorf("update product %s: %w", input.Product.ID, err) + } + + result := &SKUChangeResult{} + if input.SKUChange != nil { + result.Mode = input.SKUChange.Mode + switch input.SKUChange.Mode { + case SKUChangeModePatchExisting: + for _, item := range input.SKUChange.PatchItems { + if err := updateCurrentSKU(ctx, tx, productID, item); err != nil { + return nil, err + } + result.UpdatedSKUIds = append(result.UpdatedSKUIds, item.ID) + } + case SKUChangeModeReplaceAll: + if len(input.SKUChange.ReplaceItems) == 0 { + return nil, fmt.Errorf("replace_items must not be empty") + } + archivedIDs, err := archiveCurrentSKUs(ctx, tx, productID) + if err != nil { + return nil, err + } + result.ArchivedSKUIds = archivedIDs + for _, sku := range input.SKUChange.ReplaceItems { + createdSKU, err := insertSKU(ctx, tx, input.Product.ID, sku) + if err != nil { + return nil, err + } + result.CreatedSKUIds = append(result.CreatedSKUIds, createdSKU.ID) + } + default: + return nil, fmt.Errorf("unsupported sku change mode") + } + if err := autoOffSaleIfNoSellableSKU(ctx, tx, productID); err != nil { + return nil, err + } + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit update product: %w", err) + } + return result, nil +} + +// UpdateProductStatus changes the product lifecycle state using optimistic locking. +func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32) (*ProductStatusUpdate, error) { + if expectedVersion < 0 { + return nil, fmt.Errorf("expected product version must be non-negative") + } + if next != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && next != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && next != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { + return nil, fmt.Errorf("unsupported product status") + } + id, err := parseID(productID, "product id") + if err != nil { + return nil, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin update product status: %w", err) + } + defer tx.Rollback() + + var previousDBStatus int16 + var currentVersion int32 + err = tx.QueryRowContext(ctx, ` +SELECT status, version +FROM product.products +WHERE id = $1 AND deleted_at IS NULL +FOR UPDATE +`, id).Scan(&previousDBStatus, ¤tVersion) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductNotFound + } + if err != nil { + return nil, fmt.Errorf("lock product %s: %w", productID, err) + } + if currentVersion != expectedVersion { + return nil, ErrProductVersionConflict + } + if next == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE { + sellable, err := hasSellableSKU(ctx, tx, id) + if err != nil { + return nil, err + } + if !sellable { + return nil, fmt.Errorf("cannot put product on sale without a sellable sku") + } + } + + result := &ProductStatusUpdate{ProductID: productID, PreviousStatus: statusFromDB(previousDBStatus), Status: next} + if result.PreviousStatus == next { + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit unchanged product status: %w", err) + } + result.Version = currentVersion + return result, nil + } + if err := tx.QueryRowContext(ctx, ` +UPDATE product.products +SET status = $2, version = version + 1, updated_at = NOW() +WHERE id = $1 AND version = $3 AND deleted_at IS NULL +RETURNING version, updated_at +`, id, statusToDB(next), expectedVersion).Scan(&result.Version, &result.UpdatedAt); err != nil { + return nil, fmt.Errorf("update product status %s: %w", productID, err) + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit update product status: %w", err) + } + return result, nil +} + +func updateCurrentSKU(ctx context.Context, tx *sql.Tx, productID int64, input SKUUpdate) error { + if input.ExpectedSKUVersion < 0 || input.ExpectedInventoryVersion < 0 { + return fmt.Errorf("expected sku and inventory versions must be non-negative") + } + skuID, err := parseID(input.ID, "sku id") + if err != nil { + return err + } + var currentVersion int32 + err = tx.QueryRowContext(ctx, ` +SELECT version +FROM product.product_items +WHERE id = $1 AND product_id = $2 AND deleted_at IS NULL AND is_archived = FALSE +FOR UPDATE +`, skuID, productID).Scan(¤tVersion) + if errors.Is(err, sql.ErrNoRows) { + var archived bool + lookupErr := tx.QueryRowContext(ctx, `SELECT is_archived FROM product.product_items WHERE id = $1 AND product_id = $2`, skuID, productID).Scan(&archived) + if lookupErr == nil && archived { + return ErrSKUArchived + } + return ErrSKUNotFound + } + if err != nil { + return fmt.Errorf("lock sku %s: %w", input.ID, err) + } + if currentVersion != input.ExpectedSKUVersion { + return ErrSKUVersionConflict + } + + if input.Name != nil || input.Price != nil || input.Status != nil || input.ImageIDs != nil { + sets := []string{"updated_at = NOW()", "version = version + 1"} + args := []any{skuID, productID} + argIndex := 3 + if input.Name != nil { + if strings.TrimSpace(*input.Name) == "" { + return fmt.Errorf("sku name must not be empty") + } + sets = append(sets, fmt.Sprintf("name = $%d", argIndex)) + args = append(args, strings.TrimSpace(*input.Name)) + argIndex++ + } + if input.Price != nil { + if *input.Price < 0 { + return fmt.Errorf("sku price must be greater than or equal to 0") + } + sets = append(sets, fmt.Sprintf("price = $%d", argIndex)) + args = append(args, *input.Price) + argIndex++ + } + if input.Status != nil { + if *input.Status != 0 && *input.Status != 1 { + return fmt.Errorf("sku status must be 0 or 1") + } + sets = append(sets, fmt.Sprintf("status = $%d", argIndex)) + args = append(args, *input.Status) + argIndex++ + } + if input.ImageIDs != nil { + sets = append(sets, fmt.Sprintf("image_ids = $%d", argIndex)) + args = append(args, stringSliceOrEmpty(*input.ImageIDs)) + argIndex++ + } + query := fmt.Sprintf(`UPDATE product.product_items SET %s WHERE id = $1 AND product_id = $2 AND version = $%d`, strings.Join(sets, ", "), argIndex) + args = append(args, input.ExpectedSKUVersion) + res, err := tx.ExecContext(ctx, query, args...) + if err != nil { + return fmt.Errorf("update sku %s: %w", input.ID, err) + } + affected, err := res.RowsAffected() + if err != nil { + return fmt.Errorf("sku rows affected: %w", err) + } + if affected == 0 { + return ErrSKUVersionConflict + } + } + + if input.AvailableQuantity != nil { + if *input.AvailableQuantity < 0 { + return fmt.Errorf("available_quantity must be greater than or equal to 0") + } + var lockedQuantity int32 + var inventoryVersion int32 + err := tx.QueryRowContext(ctx, ` +SELECT locked_quantity, version +FROM product.product_item_inventory +WHERE sku_id = $1 +FOR UPDATE +`, skuID).Scan(&lockedQuantity, &inventoryVersion) + if errors.Is(err, sql.ErrNoRows) { + return ErrSKUNotFound + } + if err != nil { + return fmt.Errorf("lock sku inventory %s: %w", input.ID, err) + } + if inventoryVersion != input.ExpectedInventoryVersion { + return ErrSKUVersionConflict + } + if *input.AvailableQuantity < lockedQuantity { + return fmt.Errorf("available_quantity cannot be less than locked_quantity") + } + if _, err := tx.ExecContext(ctx, ` +UPDATE product.product_item_inventory +SET available_quantity = $2, version = version + 1, updated_at = NOW() +WHERE sku_id = $1 AND version = $3 +`, skuID, *input.AvailableQuantity, input.ExpectedInventoryVersion); err != nil { + return fmt.Errorf("update sku inventory %s: %w", input.ID, err) + } + } + return nil +} + +func archiveCurrentSKUs(ctx context.Context, tx *sql.Tx, productID int64) ([]string, error) { + rows, err := tx.QueryContext(ctx, ` +UPDATE product.product_items +SET status = 0, is_archived = TRUE, archived_at = NOW(), version = version + 1, updated_at = NOW() +WHERE product_id = $1 AND deleted_at IS NULL AND is_archived = FALSE +RETURNING id +`, productID) + if err != nil { + return nil, fmt.Errorf("archive current skus: %w", err) + } + defer rows.Close() + ids := make([]string, 0) + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, fmt.Errorf("scan archived sku id: %w", err) + } + ids = append(ids, formatID(id)) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate archived skus: %w", err) + } + return ids, nil +} + +func hasSellableSKU(ctx context.Context, tx *sql.Tx, productID int64) (bool, error) { + var exists bool + err := tx.QueryRowContext(ctx, ` +SELECT EXISTS( + SELECT 1 + FROM product.product_items pi + JOIN product.product_item_inventory inv ON inv.sku_id = pi.id + WHERE pi.product_id = $1 + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + AND inv.available_quantity > inv.locked_quantity +) +`, productID).Scan(&exists) + if err != nil { + return false, fmt.Errorf("check sellable sku: %w", err) + } + return exists, nil +} + +// autoOffSaleIfNoSellableSKU transitions an on-sale product to OFF_SALE only; it never auto-relists. +func autoOffSaleIfNoSellableSKU(ctx context.Context, tx *sql.Tx, productID int64) error { + _, err := tx.ExecContext(ctx, ` +UPDATE product.products p +SET status = $2, version = version + 1, updated_at = NOW() +WHERE p.id = $1 + AND p.deleted_at IS NULL + AND p.status = $3 + AND NOT EXISTS ( + SELECT 1 + FROM product.product_items pi + JOIN product.product_item_inventory inv ON inv.sku_id = pi.id + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + AND inv.available_quantity > inv.locked_quantity + ) +`, productID, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE)) + if err != nil { + return fmt.Errorf("auto off-sale product %s: %w", formatID(productID), err) + } + return nil +} + // DeleteProduct soft-deletes an SPU and its SKUs. func (r *ProductRepository) DeleteProduct(ctx context.Context, productID string) error { id, err := parseID(productID, "product id") @@ -616,8 +1068,8 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error res, err := tx.ExecContext(ctx, ` UPDATE product.product_items -SET sku_no = $2, name = $3, price = $4, image_ids = $5, attributes = $6::jsonb, status = $7, updated_at = NOW() -WHERE id = $1 +SET sku_no = $2, name = $3, price = $4, image_ids = $5, attributes = $6::jsonb, status = $7, version = version + 1, updated_at = NOW() +WHERE id = $1 AND is_archived = FALSE `, id, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) if err != nil { return fmt.Errorf("update sku %s: %w", sku.ID, err) @@ -651,14 +1103,50 @@ func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, qua return nil, err } - row := r.db.QueryRowContext(ctx, ` + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin lock inventory: %w", err) + } + defer tx.Rollback() + + var productID int64 + var productStatus int16 + err = tx.QueryRowContext(ctx, ` +SELECT pi.product_id, p.status +FROM product.product_items pi +JOIN product.products p ON p.id = pi.product_id +WHERE pi.id = $1 + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + AND p.deleted_at IS NULL +FOR UPDATE OF p +`, id).Scan(&productID, &productStatus) + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrSKUNotFound) + } + if err != nil { + return nil, fmt.Errorf("lock product for inventory %s: %w", skuID, err) + } + if statusFromDB(productStatus) != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE { + return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrProductNotOnSale) + } + row := tx.QueryRowContext(ctx, ` UPDATE product.product_item_inventory SET locked_quantity = locked_quantity + $2, version = version + 1, updated_at = NOW() WHERE sku_id = $1 + AND EXISTS ( + SELECT 1 + FROM product.product_items pi + WHERE pi.id = product.product_item_inventory.sku_id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + ) AND available_quantity - locked_quantity >= $2 -RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at +RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at `, id, quantity) inventory, err := scanInventory(row) if errors.Is(err, sql.ErrNoRows) { @@ -674,6 +1162,12 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create if err != nil { return nil, fmt.Errorf("lock inventory %s: %w", skuID, err) } + if err := autoOffSaleIfNoSellableSKU(ctx, tx, productID); err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit lock inventory: %w", err) + } return inventory, nil } @@ -681,7 +1175,13 @@ func (r *ProductRepository) skuInventoryExists(ctx context.Context, skuID int64) var exists bool err := r.db.QueryRowContext(ctx, ` SELECT EXISTS( - SELECT 1 FROM product.product_item_inventory WHERE sku_id = $1 + SELECT 1 + FROM product.product_item_inventory inv + JOIN product.product_items pi ON pi.id = inv.sku_id + WHERE inv.sku_id = $1 + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 ) `, skuID).Scan(&exists) if err != nil { @@ -770,6 +1270,7 @@ LEFT JOIN LATERAL ( LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id WHERE pi.product_id = p.id AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE ) sku_summary ON TRUE WHERE p.deleted_at IS NULL ORDER BY p.created_at DESC, p.id DESC @@ -795,7 +1296,7 @@ LIMIT $1 OFFSET $2 } // ListCategoryProducts loads paginated product summaries for a category ID. -func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { +func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool) ([]*CategoryProductRecord, int64, error) { parsedCategoryID, err := parseID(categoryID, "category id") if err != nil { return nil, 0, err @@ -815,7 +1316,8 @@ FROM product.products p JOIN product.product_category_bindings b ON b.product_id = p.id WHERE b.category_id = $1 AND p.deleted_at IS NULL -`, parsedCategoryID).Scan(&total); err != nil { + AND ($2 = FALSE OR p.status IN ($3, $4)) +`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE)).Scan(&total); err != nil { return nil, 0, fmt.Errorf("count category products: %w", err) } if total == 0 { @@ -842,12 +1344,14 @@ LEFT JOIN LATERAL ( LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id WHERE pi.product_id = p.id AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE ) sku_summary ON TRUE WHERE b.category_id = $1 AND p.deleted_at IS NULL + AND ($2 = FALSE OR p.status IN ($5, $6)) ORDER BY p.created_at DESC, p.id DESC -LIMIT $2 OFFSET $3 -`, parsedCategoryID, pageSize, offset) +LIMIT $3 OFFSET $4 +`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE)) if err != nil { return nil, 0, fmt.Errorf("query category products: %w", err) } @@ -981,6 +1485,7 @@ SELECT id, freight_template_id, sale_time_type, scheduled_sale_time, + version, deleted_at, created_at, updated_at @@ -1068,6 +1573,7 @@ RETURNING id, freight_template_id, sale_time_type, scheduled_sale_time, + version, deleted_at, created_at, updated_at @@ -1120,6 +1626,9 @@ RETURNING id, COALESCE(to_json(image_ids)::text, '[]'), attributes, status, + is_archived, + archived_at, + version, deleted_at, created_at, updated_at, @@ -1128,6 +1637,7 @@ RETURNING id, NULL::integer, NULL::integer, NULL::integer, + NULL::integer, NULL::timestamptz, NULL::timestamptz `, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) @@ -1172,7 +1682,7 @@ 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 = $2 -RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, created_at, updated_at +RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at `, inventoryID, skuID, availableQuantity) inventory, err := scanInventory(row) if err != nil { @@ -1185,9 +1695,10 @@ func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQ row := tx.QueryRowContext(ctx, ` UPDATE product.product_item_inventory SET available_quantity = $2, + version = version + 1, 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, version, created_at, updated_at `, skuID, availableQuantity) inventory, err := scanInventory(row) if errors.Is(err, sql.ErrNoRows) { @@ -1294,6 +1805,9 @@ SELECT pi.id, COALESCE(to_json(pi.image_ids)::text, '[]'), pi.attributes, pi.status, + pi.is_archived, + pi.archived_at, + pi.version, pi.deleted_at, pi.created_at, pi.updated_at, @@ -1302,12 +1816,14 @@ SELECT pi.id, inv.available_quantity, inv.locked_quantity, inv.sold_quantity, + inv.version, inv.created_at, inv.updated_at FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id WHERE pi.product_id IN (%s) AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE ORDER BY pi.created_at ASC `, strings.Join(placeholders, ", ")) @@ -1381,6 +1897,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { freightTemplateID sql.NullInt64 saleTimeType int16 scheduledSaleTime sql.NullTime + version int32 deletedAt sql.NullTime ) if err := scanner.Scan( @@ -1402,6 +1919,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { &freightTemplateID, &saleTimeType, &scheduledSaleTime, + &version, &deletedAt, &rec.CreatedAt, &rec.UpdatedAt, @@ -1417,6 +1935,7 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { rec.SupplierID = formatID(supplierID.Int64) } rec.GoodsType = int32(goodsType) + rec.Version = version imageIDs, err := parseStringArrayJSON(imageIDsJSON) if err != nil { return nil, fmt.Errorf("unmarshal product image_ids: %w", err) @@ -1460,12 +1979,16 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { imageIDsJSON string attrsJSON []byte status int16 + isArchived bool + archivedAt sql.NullTime + version int32 deletedAt sql.NullTime inventoryID sql.NullInt64 inventorySKUID sql.NullInt64 availableQuantity sql.NullInt32 lockedQuantity sql.NullInt32 soldQuantity sql.NullInt32 + inventoryVersion sql.NullInt32 inventoryCreatedAt sql.NullTime inventoryUpdatedAt sql.NullTime ) @@ -1478,6 +2001,9 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { &imageIDsJSON, &attrsJSON, &status, + &isArchived, + &archivedAt, + &version, &deletedAt, &rec.CreatedAt, &rec.UpdatedAt, @@ -1486,6 +2012,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { &availableQuantity, &lockedQuantity, &soldQuantity, + &inventoryVersion, &inventoryCreatedAt, &inventoryUpdatedAt, ); err != nil { @@ -1510,6 +2037,11 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { return nil, err } rec.Status = int32(status) + rec.IsArchived = isArchived + rec.Version = version + if archivedAt.Valid { + rec.ArchivedAt = timePtr(archivedAt.Time) + } if deletedAt.Valid { rec.DeletedAt = timePtr(deletedAt.Time) } @@ -1520,6 +2052,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { AvailableQuantity: nullInt32Value(availableQuantity), LockedQuantity: nullInt32Value(lockedQuantity), SoldQuantity: nullInt32Value(soldQuantity), + Version: nullInt32Value(inventoryVersion), } if inventoryCreatedAt.Valid { rec.Inventory.CreatedAt = inventoryCreatedAt.Time @@ -1546,6 +2079,7 @@ func scanInventory(scanner rowScanner) (*InventoryRecord, error) { &rec.AvailableQuantity, &rec.LockedQuantity, &rec.SoldQuantity, + &rec.Version, &rec.CreatedAt, &rec.UpdatedAt, ); err != nil { @@ -1732,22 +2266,22 @@ func timePtr(value time.Time) *time.Time { func statusToDB(status productv1.ProductStatus) int16 { switch status { - case productv1.ProductStatus_PRODUCT_STATUS_DRAFT: - return 0 - case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE: + case productv1.ProductStatus_PRODUCT_STATUS_INVENTORY: return 1 + case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE: + return 2 case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE: return 3 default: - return 0 + return 1 } } func statusFromDB(status int16) productv1.ProductStatus { switch status { - case 0: - return productv1.ProductStatus_PRODUCT_STATUS_DRAFT case 1: + return productv1.ProductStatus_PRODUCT_STATUS_INVENTORY + case 2: return productv1.ProductStatus_PRODUCT_STATUS_ON_SALE case 3: return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE diff --git a/internal/server/product_server.go b/internal/server/product_server.go index d9c1d19..4bf7bc6 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -149,6 +149,103 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc }, nil } +// UpdateProduct updates mutable SPU fields and optionally patches or replaces its SKU set. +func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.UpdateProductRequest) (*productv1.UpdateProductResponse, error) { + if req == nil || req.GetProductId() == "" { + return nil, status.Error(codes.InvalidArgument, "product_id is required") + } + if req.GetExpectedVersion() < 0 { + return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") + } + + current, _, err := s.repo.GetProduct(ctx, req.GetProductId()) + if errors.Is(err, repository.ErrProductNotFound) { + return nil, status.Error(codes.NotFound, "product not found") + } + if err != nil { + s.observer.Logger(ctx).Error("load product for update failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "load product for update: %v", err) + } + + merged, err := mergeProductUpdate(current, req.GetProduct(), req.GetUpdateMask().GetPaths()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + skuChange, err := skuChangeFromProto(req.GetSkuChange(), s.idgen) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if len(req.GetUpdateMask().GetPaths()) == 0 && skuChange == nil { + return nil, status.Error(codes.InvalidArgument, "at least one product field or sku_change is required") + } + if err := validateProductForUpdate(merged); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) + defer dbSpan.End() + result, err := s.repo.UpdateProductWithSKUChange(dbCtx, repository.ProductUpdateInput{ + Product: merged, + ExpectedVersion: req.GetExpectedVersion(), + SKUChange: skuChange, + }) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrProductNotFound): + return nil, status.Error(codes.NotFound, "product not found") + case errors.Is(err, repository.ErrProductVersionConflict), errors.Is(err, repository.ErrSKUVersionConflict): + return nil, status.Error(codes.Aborted, "product or sku version conflict") + case errors.Is(err, repository.ErrSKUReplacementRequiresNotOnSale): + return nil, status.Error(codes.FailedPrecondition, err.Error()) + case errors.Is(err, repository.ErrSKUNotFound), errors.Is(err, repository.ErrSKUArchived): + return nil, status.Error(codes.NotFound, err.Error()) + default: + s.observer.Logger(ctx).Error("update product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "update product: %v", err) + } + } + + updated, skus, err := s.repo.GetProduct(ctx, req.GetProductId()) + if err != nil { + return nil, status.Errorf(codes.Internal, "load updated product: %v", err) + } + return &productv1.UpdateProductResponse{ + Product: toProtoProduct(updated, skus), + SkuChangeResult: toProtoSKUChangeResult(result), + }, nil +} + +// UpdateProductStatus changes the product lifecycle status. +func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1.UpdateProductStatusRequest) (*productv1.UpdateProductStatusResponse, error) { + if req == nil || req.GetProductId() == "" { + return nil, status.Error(codes.InvalidArgument, "product_id is required") + } + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.status.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) + defer dbSpan.End() + updated, err := s.repo.UpdateProductStatus(dbCtx, req.GetProductId(), req.GetStatus(), req.GetExpectedVersion()) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrProductNotFound): + return nil, status.Error(codes.NotFound, "product not found") + case errors.Is(err, repository.ErrProductVersionConflict): + return nil, status.Error(codes.Aborted, "product version conflict") + default: + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + } + return &productv1.UpdateProductStatusResponse{ + ProductId: updated.ProductID, + PreviousStatus: updated.PreviousStatus, + Status: updated.Status, + Version: updated.Version, + UpdatedAt: timeToMillisString(updated.UpdatedAt), + }, nil +} + // ListProducts returns a paginated list of all non-deleted products. func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) { page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) @@ -202,7 +299,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 )) defer dbSpan.End() - products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize) + products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize, req.GetOnlyVisible()) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -473,6 +570,8 @@ func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockIn switch { case errors.Is(err, repository.ErrSKUNotFound): return nil, status.Error(codes.NotFound, "sku inventory not found") + case errors.Is(err, repository.ErrProductNotOnSale): + return nil, status.Error(codes.FailedPrecondition, "product is not on sale") case errors.Is(err, repository.ErrInsufficientStock): return nil, status.Error(codes.FailedPrecondition, "insufficient stock") default: @@ -632,7 +731,12 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P statusValue := req.GetStatus() if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { - statusValue = productv1.ProductStatus_PRODUCT_STATUS_DRAFT + statusValue = productv1.ProductStatus_PRODUCT_STATUS_INVENTORY + } + if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && + statusValue != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && + statusValue != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { + return repository.ProductRecord{}, nil, errors.New("unsupported product status") } crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo()) if err != nil { @@ -686,10 +790,200 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P } skus = append(skus, sku) } + if record.Status == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && !hasSellableSKURecord(skus) { + return repository.ProductRecord{}, nil, errors.New("on-sale product requires at least one sellable sku") + } return record, skus, nil } +func mergeProductUpdate(current *repository.ProductRecord, update *productv1.ProductUpdate, paths []string) (repository.ProductRecord, error) { + if current == nil { + return repository.ProductRecord{}, errors.New("product is required") + } + merged := *current + if len(paths) == 0 { + return merged, nil + } + if update == nil { + return repository.ProductRecord{}, errors.New("product update is required when update_mask is set") + } + for _, path := range paths { + switch path { + case "title": + merged.Title = strings.TrimSpace(update.GetTitle()) + case "selling_point": + merged.SellingPoint = strings.TrimSpace(update.GetSellingPoint()) + case "brand_id": + merged.BrandID = strings.TrimSpace(update.GetBrandId()) + case "supplier_id": + merged.SupplierID = strings.TrimSpace(update.GetSupplierId()) + case "image_ids": + merged.ImageIDs = normalizeStringList(update.GetImageIds()) + case "detail_html": + merged.DetailHTML = update.GetDetailHtml() + case "member_discount_enabled": + merged.MemberDiscountEnabled = update.GetMemberDiscountEnabled() + case "service_guarantees": + merged.ServiceGuarantees = normalizeStringList(update.GetServiceGuarantees()) + case "cross_border_info": + crossBorderJSON, err := crossBorderJSONFromProto(update.GetCrossBorderInfo()) + if err != nil { + return repository.ProductRecord{}, err + } + merged.CrossBorderJSON = crossBorderJSON + case "freight_charge_type": + merged.FreightChargeType = update.GetFreightChargeType() + case "freight_fixed_amount": + merged.FreightFixedAmount = update.GetFreightFixedAmount() + case "freight_template_id": + merged.FreightTemplateID = strings.TrimSpace(update.GetFreightTemplateId()) + case "sale_time_type": + merged.SaleTimeType = update.GetSaleTimeType() + case "scheduled_sale_time": + merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime()) + case "goods_type": + merged.GoodsType = update.GetGoodsType() + default: + return repository.ProductRecord{}, fmt.Errorf("unsupported update field %q", path) + } + } + return merged, nil +} + +func validateProductForUpdate(product repository.ProductRecord) error { + if strings.TrimSpace(product.Title) == "" { + return errors.New("title is required") + } + if product.FreightFixedAmount < 0 { + return errors.New("freight_fixed_amount must be greater than or equal to 0") + } + if product.GoodsType < 1 || product.GoodsType > 4 { + return errors.New("goods_type must be between 1 and 4") + } + if product.FreightChargeType < 1 || product.FreightChargeType > 2 { + return errors.New("freight_charge_type must be 1 or 2") + } + if product.FreightChargeType == 2 && product.FreightTemplateID == "" { + return errors.New("freight_template_id is required when freight_charge_type is 2") + } + if product.SaleTimeType < 1 || product.SaleTimeType > 2 { + return errors.New("sale_time_type must be 1 or 2") + } + if product.SaleTimeType == 2 && product.ScheduledSaleTime == nil { + return errors.New("scheduled_sale_time is required when sale_time_type is 2") + } + return nil +} + +func skuChangeFromProto(input *productv1.SKUChange, idGenerator *idgen.Generator) (*repository.SKUChange, error) { + if input == nil || input.GetMode() == productv1.SKUChangeMode_SKU_CHANGE_MODE_UNSPECIFIED { + return nil, nil + } + change := &repository.SKUChange{} + switch input.GetMode() { + case productv1.SKUChangeMode_SKU_CHANGE_MODE_PATCH_EXISTING: + if len(input.GetPatchItems()) == 0 || len(input.GetReplaceItems()) != 0 { + return nil, errors.New("PATCH_EXISTING requires patch_items only") + } + change.Mode = repository.SKUChangeModePatchExisting + change.PatchItems = make([]repository.SKUUpdate, 0, len(input.GetPatchItems())) + for index, item := range input.GetPatchItems() { + if item == nil || strings.TrimSpace(item.GetSkuId()) == "" { + return nil, fmt.Errorf("patch_items[%d].sku_id is required", index) + } + update, err := skuUpdateFromProto(item) + if err != nil { + return nil, fmt.Errorf("patch_items[%d]: %w", index, err) + } + change.PatchItems = append(change.PatchItems, update) + } + case productv1.SKUChangeMode_SKU_CHANGE_MODE_REPLACE_ALL: + if len(input.GetReplaceItems()) == 0 || len(input.GetPatchItems()) != 0 { + return nil, errors.New("REPLACE_ALL requires replace_items only") + } + if idGenerator == nil { + return nil, errors.New("id generator is not configured") + } + change.Mode = repository.SKUChangeModeReplaceAll + change.ReplaceItems = make([]repository.SKURecord, 0, len(input.GetReplaceItems())) + for index, item := range input.GetReplaceItems() { + sku, err := skuFromCreateInput(item) + if err != nil { + return nil, fmt.Errorf("replace_items[%d]: %w", index, err) + } + sku.ID = idGenerator.NextString() + sku.Inventory = &repository.InventoryRecord{ID: idGenerator.NextString()} + change.ReplaceItems = append(change.ReplaceItems, sku) + } + default: + return nil, errors.New("unsupported sku change mode") + } + return change, nil +} + +func skuUpdateFromProto(input *productv1.PatchExistingSKU) (repository.SKUUpdate, error) { + paths := input.GetUpdateMask().GetPaths() + if len(paths) == 0 { + return repository.SKUUpdate{}, errors.New("update_mask is required") + } + update := repository.SKUUpdate{ + ID: strings.TrimSpace(input.GetSkuId()), + ExpectedSKUVersion: input.GetExpectedSkuVersion(), + ExpectedInventoryVersion: input.GetExpectedInventoryVersion(), + } + for _, path := range paths { + switch path { + case "name": + value := input.GetName() + update.Name = &value + case "price": + value := input.GetPrice() + update.Price = &value + case "available_quantity": + value := input.GetAvailableQuantity() + update.AvailableQuantity = &value + case "status": + value := input.GetStatus() + update.Status = &value + case "image_ids": + value := normalizeStringList(input.GetImageIds()) + update.ImageIDs = &value + default: + return repository.SKUUpdate{}, fmt.Errorf("unsupported sku update field %q", path) + } + } + return update, nil +} + +func toProtoSKUChangeResult(result *repository.SKUChangeResult) *productv1.SKUChangeResult { + if result == nil { + return nil + } + mode := productv1.SKUChangeMode_SKU_CHANGE_MODE_UNSPECIFIED + switch result.Mode { + case repository.SKUChangeModePatchExisting: + mode = productv1.SKUChangeMode_SKU_CHANGE_MODE_PATCH_EXISTING + case repository.SKUChangeModeReplaceAll: + mode = productv1.SKUChangeMode_SKU_CHANGE_MODE_REPLACE_ALL + } + return &productv1.SKUChangeResult{ + Mode: mode, + CreatedSkuIds: result.CreatedSKUIds, + ArchivedSkuIds: result.ArchivedSKUIds, + UpdatedSkuIds: result.UpdatedSKUIds, + } +} + +func hasSellableSKURecord(skus []repository.SKURecord) bool { + for _, sku := range skus { + if sku.Status == 1 && sku.AvailableQuantity > 0 { + return true + } + } + return false +} + func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, error) { if sku == nil { return repository.SKURecord{}, errors.New("sku is required") @@ -702,10 +996,14 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0") } - attrs, name, err := buildSKUAttributesAndName(sku) + attrs, derivedName, err := buildSKUAttributesAndName(sku) if err != nil { return repository.SKURecord{}, err } + name := strings.TrimSpace(sku.GetName()) + if name == "" { + name = derivedName + } statusValue := sku.GetStatus() if statusValue == 0 { statusValue = 1 @@ -876,10 +1174,10 @@ func timeToMillisString(value time.Time) string { } func timePtrToMillisString(value *time.Time) *string { - millis := "" - if value != nil { - millis = timeToMillisString(*value) + if value == nil { + return nil } + millis := timeToMillisString(*value) return &millis } @@ -918,6 +1216,9 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco V2: sku.V2, K3: sku.K3, V3: sku.V3, + IsArchived: sku.IsArchived, + ArchivedAt: timePtrToMillisString(sku.ArchivedAt), + Version: sku.Version, DeletedAt: timePtrToMillisString(sku.DeletedAt), CreatedAt: timeToMillisString(sku.CreatedAt), UpdatedAt: timeToMillisString(sku.UpdatedAt), @@ -948,6 +1249,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco FreightTemplateId: product.FreightTemplateID, SaleTimeType: product.SaleTimeType, ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), + Version: product.Version, DeletedAt: timePtrToMillisString(product.DeletedAt), } } @@ -979,6 +1281,7 @@ func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductI AvailableQuantity: inventory.AvailableQuantity, LockedQuantity: inventory.LockedQuantity, SoldQuantity: inventory.SoldQuantity, + Version: inventory.Version, CreatedAt: timeToMillisString(inventory.CreatedAt), UpdatedAt: timeToMillisString(inventory.UpdatedAt), } diff --git a/scripts/sql/migrate-product-status-and-sku-archive.sql b/scripts/sql/migrate-product-status-and-sku-archive.sql new file mode 100644 index 0000000..e2ad4c6 --- /dev/null +++ b/scripts/sql/migrate-product-status-and-sku-archive.sql @@ -0,0 +1,54 @@ +-- One-time migration for product lifecycle statuses and SKU archival. +-- Run during a maintenance window before deploying the product-service code +-- that uses PRODUCT_STATUS_INVENTORY / ON_SALE / OFF_SALE. + +BEGIN; + +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS is_archived BOOLEAN NOT NULL DEFAULT FALSE; + +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ; + +ALTER TABLE product.product_items + DROP CONSTRAINT IF EXISTS chk_product_items_archived; + +ALTER TABLE product.product_items + ADD CONSTRAINT chk_product_items_archived + CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL)); + +ALTER TABLE product.products + DROP CONSTRAINT IF EXISTS chk_products_status; + +-- Current values are 0=DRAFT, 1=ON_SALE, 3=OFF_SALE. Value 2 has no +-- supported current meaning and is moved to INVENTORY as the safe state. +UPDATE product.products +SET status = CASE status + WHEN 0 THEN 1 + WHEN 1 THEN 2 + WHEN 3 THEN 3 + ELSE 1 +END; + +ALTER TABLE product.products + ALTER COLUMN status SET DEFAULT 1; + +ALTER TABLE product.products + ADD CONSTRAINT chk_products_status CHECK (status IN (1, 2, 3)); + +COMMIT; + +-- CREATE INDEX CONCURRENTLY cannot run inside the transaction above. +CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_product_items_sku_no_active + ON product.product_items (sku_no) + WHERE sku_no IS NOT NULL + AND deleted_at IS NULL + AND is_archived = FALSE; + +CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_items_active_product_id + ON product.product_items (product_id) + WHERE deleted_at IS NULL + AND is_archived = FALSE; + +-- Drop the legacy index only after uq_product_items_sku_no_active is valid. +DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no; diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 01d20d5..4c52842 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -47,7 +47,7 @@ CREATE TABLE IF NOT EXISTS product.products ( member_discount_enabled BOOLEAN NOT NULL DEFAULT TRUE, goods_type SMALLINT NOT NULL DEFAULT 1, service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], - status SMALLINT NOT NULL DEFAULT 0, + status SMALLINT NOT NULL DEFAULT 1, cross_border JSONB NOT NULL DEFAULT '{}'::JSONB, freight_charge_type SMALLINT NOT NULL DEFAULT 1, freight_fixed_amount BIGINT NOT NULL DEFAULT 0, @@ -61,7 +61,7 @@ CREATE TABLE IF NOT EXISTS product.products ( CONSTRAINT chk_products_goods_type CHECK (goods_type IN (1, 2, 3, 4)), CONSTRAINT chk_products_status - CHECK (status IN (0, 1, 2, 3)), + CHECK (status IN (1, 2, 3)), CONSTRAINT chk_products_freight_charge_type CHECK (freight_charge_type IN (1, 2)), CONSTRAINT chk_products_freight_fixed_amount @@ -166,10 +166,14 @@ CREATE TABLE IF NOT EXISTS product.product_items ( image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], attributes JSONB NOT NULL DEFAULT '{}', status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), + is_archived BOOLEAN NOT NULL DEFAULT FALSE, + archived_at TIMESTAMPTZ, version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), deleted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT chk_product_items_archived + CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL)) ); COMMENT ON TABLE product.product_items IS '商品 SKU 明细表:存储具体可售规格、价格和规格属性;库存统一存储在 product.product_item_inventory'; @@ -177,20 +181,22 @@ 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.is_archived IS 'SKU 是否归档;归档 SKU 不参与当前运营、展示和新订单销售'; +COMMENT ON COLUMN product.product_items.archived_at IS 'SKU 归档时间;归档后仅保留供历史订单结算与展示'; COMMENT ON COLUMN product.product_items.version IS 'SKU 乐观锁版本号'; COMMENT ON COLUMN product.product_items.deleted_at IS 'SKU 软删除时间;NULL 表示未删除'; CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items (product_id) - WHERE deleted_at IS NULL; + WHERE deleted_at IS NULL AND is_archived = FALSE; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items (price) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no +CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active ON product.product_items (sku_no) - WHERE sku_no IS NOT NULL AND deleted_at IS NULL; + WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE; CREATE TABLE IF NOT EXISTS product.product_item_inventory ( id BIGINT PRIMARY KEY, From 6856553440425710ae45dd0aeac51eb3c3e3f76f Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Thu, 6 Aug 2026 12:37:38 +0800 Subject: [PATCH 30/44] feat(product): add CountProducts method to retrieve aggregate product counts by lifecycle status --- internal/repository/product_repository.go | 34 +++++++++++++++++++++++ internal/server/product_server.go | 23 +++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 4313658..0c688a5 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -74,6 +74,16 @@ type ProductRecord struct { UpdatedAt time.Time } +// ProductCountRecord contains aggregate counts for product.products. +type ProductCountRecord struct { + Total int64 + Active int64 + Draft int64 + OnSale int64 + OffSale int64 + Deleted int64 +} + // SKURecord is the persistence model for product.product_items. type SKURecord struct { ID string @@ -1295,6 +1305,30 @@ LIMIT $1 OFFSET $2 return products, total, nil } +// CountProducts returns aggregate product counts grouped by lifecycle status. +func (r *ProductRepository) CountProducts(ctx context.Context) (*ProductCountRecord, error) { + var counts ProductCountRecord + if err := r.db.QueryRowContext(ctx, ` +SELECT COUNT(*) AS total, + COUNT(*) FILTER (WHERE deleted_at IS NULL) AS active, + COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 0) AS draft, + COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 1) AS on_sale, + COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 3) AS off_sale, + COUNT(*) FILTER (WHERE deleted_at IS NOT NULL) AS deleted +FROM product.products +`).Scan( + &counts.Total, + &counts.Active, + &counts.Draft, + &counts.OnSale, + &counts.OffSale, + &counts.Deleted, + ); err != nil { + return nil, fmt.Errorf("count products: %w", err) + } + return &counts, nil +} + // ListCategoryProducts loads paginated product summaries for a category ID. func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool) ([]*CategoryProductRecord, int64, error) { parsedCategoryID, err := parseID(categoryID, "category id") diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 4bf7bc6..800a1c8 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -336,6 +336,29 @@ func normalizedPage(page, pageSize int32) (int32, int32) { return page, pageSize } +// CountProducts returns product counts grouped by lifecycle status. +func (s *ProductServer) CountProducts(ctx context.Context, req *productv1.CountProductsRequest) (*productv1.CountProductsResponse, error) { + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.count") + defer dbSpan.End() + + counts, err := s.repo.CountProducts(dbCtx) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("count products failed", zap.Error(err)) + return nil, status.Errorf(codes.Internal, "count products: %v", err) + } + + return &productv1.CountProductsResponse{ + Total: counts.Total, + Active: counts.Active, + Draft: counts.Draft, + OnSale: counts.OnSale, + OffSale: counts.OffSale, + Deleted: counts.Deleted, + }, 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 From 0186633d73b6d626b9bb0a49cc0c532ee517f42c Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Tue, 11 Aug 2026 14:58:51 +0800 Subject: [PATCH 31/44] =?UTF-8?q?feat(product):=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E8=B4=AD=E7=89=A9=E8=BD=A6=E5=95=86=E5=93=81=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/repository/product_repository.go | 144 ++++++++++++++++++++++ internal/server/product_server.go | 102 ++++++++++++++- 2 files changed, 243 insertions(+), 3 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 0c688a5..e36ce03 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -124,6 +124,22 @@ type InventoryRecord struct { UpdatedAt time.Time } +// CartItemProductLookup identifies the SPU/SKU pair stored by one cart line. +// Line IDs are intentionally kept outside the repository because they belong to trade.cart_items. +type CartItemProductLookup struct { + ProductID string + SKUID string +} + +// CartItemProductRecord contains the current catalog facts for one cart lookup. +// A nil Product or SKU means the corresponding record is missing or soft deleted. +type CartItemProductRecord struct { + ProductID string + SKUID string + Product *ProductRecord + SKU *SKURecord +} + // SKUChangeMode selects how SKU input is applied during a product update. type SKUChangeMode int32 @@ -1240,6 +1256,66 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* return product, skus[productID], nil } +// BatchGetCartItemProducts loads current catalog facts for cart lines in request order. +// It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable. +func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup) ([]CartItemProductRecord, error) { + if len(lookups) == 0 { + return []CartItemProductRecord{}, nil + } + + productIDs := make([]string, 0, len(lookups)) + skuIDs := make([]string, 0, len(lookups)) + seenProductIDs := make(map[string]struct{}, len(lookups)) + seenSKUIDs := make(map[string]struct{}, len(lookups)) + for _, lookup := range lookups { + if _, err := parseID(lookup.ProductID, "product id"); err != nil { + return nil, err + } + if _, err := parseID(lookup.SKUID, "sku id"); err != nil { + return nil, err + } + if _, ok := seenProductIDs[lookup.ProductID]; !ok { + seenProductIDs[lookup.ProductID] = struct{}{} + productIDs = append(productIDs, lookup.ProductID) + } + if _, ok := seenSKUIDs[lookup.SKUID]; !ok { + seenSKUIDs[lookup.SKUID] = struct{}{} + skuIDs = append(skuIDs, lookup.SKUID) + } + } + + products, err := r.loadProductsByIDs(ctx, productIDs) + if err != nil { + return nil, err + } + skus, err := r.loadCartItemSKUsByIDs(ctx, skuIDs) + if err != nil { + return nil, err + } + + productsByID := make(map[string]*ProductRecord, len(products)) + for _, product := range products { + productsByID[product.ID] = product + } + skusByID := make(map[string]*SKURecord, len(skus)) + for index := range skus { + skusByID[skus[index].ID] = &skus[index] + } + + results := make([]CartItemProductRecord, 0, len(lookups)) + for _, lookup := range lookups { + result := CartItemProductRecord{ProductID: lookup.ProductID, SKUID: lookup.SKUID} + result.Product = productsByID[lookup.ProductID] + if result.Product != nil { + if sku := skusByID[lookup.SKUID]; sku != nil && sku.ProductID == lookup.ProductID { + result.SKU = sku + } + } + results = append(results, result) + } + return results, nil +} + // ListProducts loads paginated summaries for all non-deleted products. func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { if page < 1 { @@ -1881,6 +1957,74 @@ ORDER BY pi.created_at ASC return result, nil } +// loadCartItemSKUsByIDs loads current and archived SKU rows used by cart display. +// Soft-deleted rows remain excluded so they are represented as missing to callers. +func (r *ProductRepository) loadCartItemSKUsByIDs(ctx context.Context, skuIDs []string) ([]SKURecord, error) { + if len(skuIDs) == 0 { + return []SKURecord{}, nil + } + + placeholders := make([]string, len(skuIDs)) + args := make([]any, len(skuIDs)) + for i, id := range skuIDs { + parsed, err := parseID(id, "sku id") + if err != nil { + return nil, err + } + placeholders[i] = fmt.Sprintf("$%d", i+1) + args[i] = parsed + } + + query := fmt.Sprintf(` +SELECT pi.id, + pi.product_id, + pi.sku_no, + pi.name, + pi.price, + COALESCE(to_json(pi.image_ids)::text, '[]'), + pi.attributes, + pi.status, + pi.is_archived, + pi.archived_at, + pi.version, + pi.deleted_at, + pi.created_at, + pi.updated_at, + inv.id, + inv.sku_id, + inv.available_quantity, + inv.locked_quantity, + inv.sold_quantity, + inv.version, + inv.created_at, + inv.updated_at +FROM product.product_items pi +LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id +WHERE pi.id IN (%s) + AND pi.deleted_at IS NULL +ORDER BY pi.created_at ASC, pi.id ASC +`, strings.Join(placeholders, ", ")) + + rows, err := r.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("query cart item skus: %w", err) + } + defer rows.Close() + + skus := make([]SKURecord, 0, len(skuIDs)) + for rows.Next() { + sku, err := scanSKU(rows) + if err != nil { + return nil, err + } + skus = append(skus, *sku) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate cart item skus: %w", err) + } + return skus, nil +} + type rowScanner interface { Scan(dest ...any) error } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 800a1c8..97f6c5e 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -33,9 +33,10 @@ const ( categoryNodeType = int32(0) groupNodeType = int32(1) - defaultNodeStatus = int32(1) - maxNodeNameLength = 100 - maxProductsPerGroupRequest = 100 + defaultNodeStatus = int32(1) + maxNodeNameLength = 100 + maxProductsPerGroupRequest = 100 + maxCartItemProductBatchSize = 100 ) // ProductServer implements productv1.ProductServiceServer. @@ -149,6 +150,72 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc }, nil } +// BatchGetCartItemProduct returns current SPU/SKU facts for cart rows in request order. +// Missing and soft-deleted records are represented by their default invalid state rather +// than failing the whole batch; malformed requests still return InvalidArgument. +func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *productv1.BatchGetCartItemProductRequest) (*productv1.BatchGetCartItemProductResponse, error) { + if req == nil || len(req.GetItems()) == 0 { + return nil, status.Error(codes.InvalidArgument, "items is required") + } + if len(req.GetItems()) > maxCartItemProductBatchSize { + return nil, status.Errorf(codes.InvalidArgument, "items must contain at most %d entries", maxCartItemProductBatchSize) + } + + lookups := make([]repository.CartItemProductLookup, 0, len(req.GetItems())) + lineIDs := make(map[string]struct{}, len(req.GetItems())) + for index, item := range req.GetItems() { + if item == nil { + return nil, status.Errorf(codes.InvalidArgument, "items[%d] is required", index) + } + if err := validatePositiveID(item.GetLineId(), "line_id"); err != nil { + return nil, status.Errorf(codes.InvalidArgument, "items[%d]: %v", index, err) + } + if _, exists := lineIDs[item.GetLineId()]; exists { + return nil, status.Errorf(codes.InvalidArgument, "items[%d]: duplicate line_id", index) + } + lineIDs[item.GetLineId()] = struct{}{} + if err := validatePositiveID(item.GetProductId(), "product_id"); err != nil { + return nil, status.Errorf(codes.InvalidArgument, "items[%d]: %v", index, err) + } + if err := validatePositiveID(item.GetSkuId(), "sku_id"); err != nil { + return nil, status.Errorf(codes.InvalidArgument, "items[%d]: %v", index, err) + } + if item.GetQuantity() <= 0 { + return nil, status.Errorf(codes.InvalidArgument, "items[%d]: quantity must be positive", index) + } + lookups = append(lookups, repository.CartItemProductLookup{ + ProductID: item.GetProductId(), + SKUID: item.GetSkuId(), + }) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.cart_item.batch_get", trace.WithAttributes( + attribute.Int("product.cart_item_count", len(lookups)), + )) + defer dbSpan.End() + + records, err := s.repo.BatchGetCartItemProducts(dbCtx, lookups) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("batch get cart item products failed", zap.Error(err)) + return nil, status.Errorf(codes.Internal, "batch get cart item products: %v", err) + } + if len(records) != len(req.GetItems()) { + err := fmt.Errorf("repository returned %d records for %d lookups", len(records), len(req.GetItems())) + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("batch get cart item products incomplete", zap.Error(err)) + return nil, status.Error(codes.Internal, "batch get cart item products returned incomplete data") + } + + items := make([]*productv1.CartItemProduct, 0, len(records)) + for index, record := range records { + items = append(items, toProtoCartItemProduct(req.GetItems()[index].GetLineId(), record)) + } + return &productv1.BatchGetCartItemProductResponse{Items: items}, nil +} + // UpdateProduct updates mutable SPU fields and optionally patches or replaces its SKU set. func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.UpdateProductRequest) (*productv1.UpdateProductResponse, error) { if req == nil || req.GetProductId() == "" { @@ -1277,6 +1344,35 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco } } +func toProtoCartItemProduct(lineID string, record repository.CartItemProductRecord) *productv1.CartItemProduct { + result := &productv1.CartItemProduct{ + LineId: lineID, + ProductId: record.ProductID, + SkuId: record.SKUID, + SpuStatus: productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED, + } + if record.Product == nil { + return result + } + + result.ProductName = record.Product.Title + result.ServiceGuarantees = record.Product.ServiceGuarantees + result.SpuImageIds = record.Product.ImageIDs + result.SpuStatus = record.Product.Status + if record.SKU == nil { + return result + } + + result.SkuName = record.SKU.Name + result.Price = record.SKU.Price + result.SkuImageIds = record.SKU.ImageIDs + result.SkuAvailableQuantity = record.SKU.AvailableQuantity + result.SkuLockedQuantity = record.SKU.LockedQuantity + result.SkuStatus = record.SKU.Status + result.SkuIsArchived = record.SKU.IsArchived + return result +} + func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv1.CategoryProduct { if product == nil { return nil From d75d6e211292a1642a23af4ccd2af49489dd0437 Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Wed, 12 Aug 2026 09:35:46 +0800 Subject: [PATCH 32/44] feat(category): add batch category tree update with optimistic locking --- internal/repository/product_repository.go | 169 ++++++++++++++++++++- internal/server/product_server.go | 172 ++++++++++++++++++++++ scripts/sql/recreate-product-tables.sql | 6 +- 3 files changed, 342 insertions(+), 5 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index e36ce03..18624a8 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -20,6 +20,8 @@ var ErrProductNotFound = errors.New("product not found") // ErrCategoryNodeNotFound is returned when a category or product group node does not exist. var ErrCategoryNodeNotFound = errors.New("category or group node not found") +var ErrCategoryVersionConflict = errors.New("category version conflict") +var ErrCategoryTreeConflict = errors.New("category tree conflict") // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") @@ -214,6 +216,24 @@ type CategoryRecord struct { ImageIDs []string SortNum int32 Status int32 + Version int32 +} + +// CategoryFieldUpdate selects mutable fields of one category node. +type CategoryFieldUpdate struct { + ID string + ExpectedVersion int32 + Name *string + ImageIDs *[]string + SortNum *int32 + Status *int32 +} + +// CategoryTreeUpdate groups an optional root update with direct-child updates. +type CategoryTreeUpdate struct { + CategoryID string + Category *CategoryFieldUpdate + Children []CategoryFieldUpdate } // ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. @@ -238,6 +258,21 @@ ALTER TABLE product.product_category_bindings ALTER TABLE product.product_category ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; +ALTER TABLE product.product_category + ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0; + +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conname = 'chk_product_category_version' + AND connamespace = 'product'::regnamespace + ) THEN + ALTER TABLE product.product_category + ADD CONSTRAINT chk_product_category_version CHECK (version >= 0); + END IF; +END $$; + DO $$ BEGIN IF EXISTS ( @@ -428,6 +463,129 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat return createdCategory, nil } +// UpdateCategoryTrees applies all requested root and direct-child patches in a +// single transaction. Callers must supply already-validated patch fields. +func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate) error { + if len(updates) == 0 { + return errors.New("category_trees is required") + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin update category trees: %w", err) + } + defer tx.Rollback() + + for _, tree := range updates { + root, err := loadCategoryForUpdate(ctx, tx, tree.CategoryID) + if err != nil { + return err + } + if root.NodeType != 0 || root.Level != 1 || root.ParentID != "" { + return ErrCategoryTreeConflict + } + if tree.Category != nil { + if tree.Category.ID != tree.CategoryID { + return ErrCategoryTreeConflict + } + if _, err := updateCategoryFields(ctx, tx, *tree.Category); err != nil { + return err + } + } + for _, child := range tree.Children { + current, err := loadCategoryForUpdate(ctx, tx, child.ID) + if err != nil { + return err + } + if current.NodeType != 0 || current.Level != 2 || current.ParentID != tree.CategoryID { + return ErrCategoryTreeConflict + } + if _, err := updateCategoryFields(ctx, tx, child); err != nil { + return err + } + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit update category trees: %w", err) + } + return nil +} + +func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string) (*CategoryRecord, error) { + id, err := parseID(categoryID, "category_id") + if err != nil { + return nil, err + } + row := tx.QueryRowContext(ctx, ` +SELECT id, node_type, name, parent_id, level, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version +FROM product.product_category +WHERE id = $1 +FOR UPDATE`, id) + category, err := scanCategory(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrCategoryNodeNotFound + } + if err != nil { + return nil, fmt.Errorf("load category for update: %w", err) + } + return category, nil +} + +func updateCategoryFields(ctx context.Context, tx *sql.Tx, update CategoryFieldUpdate) (*CategoryRecord, error) { + if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil { + return nil, errors.New("category update has no fields") + } + id, err := parseID(update.ID, "category_id") + if err != nil { + return nil, err + } + row := tx.QueryRowContext(ctx, ` +UPDATE product.product_category +SET name = CASE WHEN $3 THEN $4 ELSE name END, + image_ids = CASE WHEN $5 THEN $6 ELSE image_ids END, + sort_num = CASE WHEN $7 THEN $8 ELSE sort_num END, + status = CASE WHEN $9 THEN $10 ELSE status END, + version = version + 1 +WHERE id = $1 AND version = $2 +RETURNING id, node_type, name, parent_id, level, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version`, + id, update.ExpectedVersion, + update.Name != nil, stringValue(update.Name), + update.ImageIDs != nil, stringSliceOrEmpty(pointerStringSlice(update.ImageIDs)), + update.SortNum != nil, int32Value(update.SortNum), + update.Status != nil, int32Value(update.Status), + ) + category, err := scanCategory(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrCategoryVersionConflict + } + if err != nil { + return nil, fmt.Errorf("update category fields: %w", err) + } + return category, nil +} + +func stringValue(value *string) string { + if value == nil { + return "" + } + return *value +} + +func int32Value(value *int32) int32 { + if value == nil { + return 0 + } + return *value +} + +func pointerStringSlice(value *[]string) []string { + if value == nil { + return nil + } + return *value +} + // AddProductsToGroup binds every product to the requested category or product group in one transaction. // Existing bindings are retained and duplicate bindings are ignored. func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string) error { @@ -1491,7 +1649,8 @@ SELECT id, level, COALESCE(to_json(image_ids)::text, '[]'), sort_num, - status + status, + version FROM product.product_category WHERE node_type = 0 AND ($1 = false OR status = 1) @@ -1527,7 +1686,8 @@ SELECT id, level, COALESCE(to_json(image_ids)::text, '[]'), sort_num, - status + status, + version FROM product.product_category WHERE node_type = 1 AND ($1 = false OR status = 1) @@ -1879,7 +2039,8 @@ RETURNING id, level, COALESCE(to_json(image_ids)::text, '[]'), sort_num, - status + status, + version `, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status)) createdCategory, err := scanCategory(row) @@ -2279,7 +2440,7 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { status int16 ) if err := scanner.Scan( - &id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, + &id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &rec.Version, ); err != nil { return nil, fmt.Errorf("scan category: %w", err) } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 97f6c5e..6bca0a7 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "math" + "sort" "strconv" "strings" "time" @@ -17,6 +18,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/fieldmaskpb" "google.golang.org/protobuf/types/known/timestamppb" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" @@ -495,6 +497,51 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C }, nil } +// UpdateCategoryTrees atomically updates one or more top-level category trees. +func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.UpdateCategoryTreesRequest) (*productv1.UpdateCategoryTreesResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + updates, rootIDs, err := categoryTreeUpdatesFromRequest(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates)))) + defer dbSpan.End() + if err := s.repo.UpdateCategoryTrees(dbCtx, updates); err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrCategoryNodeNotFound): + return nil, status.Error(codes.NotFound, "category not found") + case errors.Is(err, repository.ErrCategoryVersionConflict): + return nil, status.Error(codes.Aborted, "category version conflict") + case errors.Is(err, repository.ErrCategoryTreeConflict): + return nil, status.Error(codes.FailedPrecondition, "child category does not belong to the specified top-level category") + default: + s.observer.Logger(ctx).Error("update category trees failed", zap.Error(err)) + return nil, status.Error(codes.Internal, "update category trees") + } + } + all, err := s.repo.ListCategoryTreeNodes(dbCtx, false) + if err != nil { + return nil, status.Error(codes.Internal, "load updated category trees") + } + rootsByID := make(map[string]*productv1.CategoryNode) + for _, root := range buildCategoryTree(all) { + rootsByID[root.GetCategoryId()] = root + } + categories := make([]*productv1.CategoryNode, 0, len(rootIDs)) + for _, rootID := range rootIDs { + root := rootsByID[rootID] + if root == nil { + return nil, status.Error(codes.Internal, "updated category tree is missing") + } + categories = append(categories, root) + } + return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil +} + // CreateGroup creates a top-level product group. func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) { if req == nil { @@ -751,6 +798,130 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re return parent, children, nil } +func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ([]repository.CategoryTreeUpdate, []string, error) { + if len(req.GetCategoryTrees()) == 0 { + return nil, nil, errors.New("category_trees is required") + } + updates := make([]repository.CategoryTreeUpdate, 0, len(req.GetCategoryTrees())) + rootIDs := make([]string, 0, len(req.GetCategoryTrees())) + seenRoots := make(map[string]struct{}, len(req.GetCategoryTrees())) + seenChildren := make(map[string]struct{}) + for _, tree := range req.GetCategoryTrees() { + if tree == nil { + return nil, nil, errors.New("category_trees item is required") + } + rootID, err := normalizeCategoryID(tree.GetCategoryId(), "category_trees.category_id") + if err != nil { + return nil, nil, err + } + if _, exists := seenRoots[rootID]; exists { + return nil, nil, errors.New("category_trees.category_id must be unique") + } + seenRoots[rootID] = struct{}{} + update := repository.CategoryTreeUpdate{CategoryID: rootID} + if tree.GetCategory() != nil { + patch, err := categoryFieldUpdateFromProto(rootID, tree.GetCategory(), "category") + if err != nil { + return nil, nil, err + } + update.Category = patch + } + for _, child := range tree.GetChildCategories() { + if child == nil { + return nil, nil, errors.New("child_categories item is required") + } + childID, err := normalizeCategoryID(child.GetCategoryId(), "child_categories.category_id") + if err != nil { + return nil, nil, err + } + if _, exists := seenChildren[childID]; exists { + return nil, nil, errors.New("child category_id must not appear more than once") + } + seenChildren[childID] = struct{}{} + patch, err := categoryFieldUpdateFromProto(childID, child.GetPatch(), "child_categories.patch") + if err != nil { + return nil, nil, err + } + update.Children = append(update.Children, *patch) + } + if update.Category == nil && len(update.Children) == 0 { + return nil, nil, errors.New("category tree patch must update category or child_categories") + } + sort.Slice(update.Children, func(i, j int) bool { return update.Children[i].ID < update.Children[j].ID }) + updates = append(updates, update) + rootIDs = append(rootIDs, rootID) + } + // A stable lock order avoids deadlocks when two edits overlap roots. + sort.Slice(updates, func(i, j int) bool { return updates[i].CategoryID < updates[j].CategoryID }) + return updates, rootIDs, nil +} + +func categoryFieldUpdateFromProto(id string, patch *productv1.CategoryFieldPatch, field string) (*repository.CategoryFieldUpdate, error) { + if patch == nil { + return nil, fmt.Errorf("%s is required", field) + } + paths, err := categoryUpdatePaths(patch.GetUpdateMask()) + if err != nil { + return nil, fmt.Errorf("%s: %w", field, err) + } + if patch.GetExpectedVersion() < 0 { + return nil, fmt.Errorf("%s.expected_version must be non-negative", field) + } + update := &repository.CategoryFieldUpdate{ID: id, ExpectedVersion: patch.GetExpectedVersion()} + for _, path := range paths { + switch path { + case "name": + value, err := normalizeNodeName(patch.GetName(), field+".name") + if err != nil { + return nil, err + } + update.Name = &value + case "image_ids": + value := normalizeStringList(patch.GetImageIds()) + update.ImageIDs = &value + case "sort_num": + value := patch.GetSortNum() + update.SortNum = &value + case "status": + value := patch.GetStatus() + if value != 0 && value != 1 { + return nil, fmt.Errorf("%s.status must be 0 or 1", field) + } + update.Status = &value + } + } + return update, nil +} + +func categoryUpdatePaths(mask *fieldmaskpb.FieldMask) ([]string, error) { + if mask == nil || len(mask.GetPaths()) == 0 { + return nil, errors.New("update_mask is required") + } + allowed := map[string]struct{}{"name": {}, "image_ids": {}, "sort_num": {}, "status": {}} + paths := make([]string, 0, len(mask.GetPaths())) + seen := make(map[string]struct{}, len(mask.GetPaths())) + for _, path := range mask.GetPaths() { + if _, ok := allowed[path]; !ok { + return nil, fmt.Errorf("unsupported update path %q", path) + } + if _, duplicate := seen[path]; duplicate { + return nil, fmt.Errorf("duplicate update path %q", path) + } + seen[path] = struct{}{} + paths = append(paths, path) + } + return paths, nil +} + +func normalizeCategoryID(value, field string) (string, error) { + trimmed := strings.TrimSpace(value) + id, err := strconv.ParseInt(trimmed, 10, 64) + if err != nil || id <= 0 { + return "", fmt.Errorf("%s must be a positive snowflake id", field) + } + return trimmed, nil +} + func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, error) { name, err := normalizeNodeName(req.GetName(), "name") if err != nil { @@ -1455,6 +1626,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor ImageJson: categoryImageIDsJSON(category.ImageIDs), SortNum: category.SortNum, Status: category.Status, + Version: category.Version, Children: []*productv1.CategoryNode{}, } } diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 4c52842..b777ebf 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -118,12 +118,15 @@ CREATE TABLE IF NOT EXISTS product.product_category ( image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], sort_num INTEGER NOT NULL DEFAULT 0, status SMALLINT NOT NULL DEFAULT 1, + version INTEGER NOT NULL DEFAULT 0, CONSTRAINT chk_product_category_node_type CHECK (node_type IN (0, 1)), CONSTRAINT chk_product_category_level CHECK (level > 0), CONSTRAINT chk_product_category_status - CHECK (status IN (0, 1)) + CHECK (status IN (0, 1)), + CONSTRAINT chk_product_category_version + CHECK (version >= 0) ); COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组'; @@ -135,6 +138,7 @@ COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、 COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前'; COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示'; +COMMENT ON COLUMN product.product_category.version IS '节点乐观锁版本号,更新时递增'; CREATE INDEX IF NOT EXISTS idx_product_category_parent_id ON product.product_category (parent_id); From 9e9c66fc428496e2d9d2375f04298bb2119fd9fc Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Wed, 12 Aug 2026 18:42:01 +0800 Subject: [PATCH 33/44] =?UTF-8?q?feat:=20=E7=BB=9F=E4=B8=80=E5=95=86?= =?UTF-8?q?=E5=93=81=E3=80=81=E5=AE=A2=E6=88=B7=E3=80=81=E6=B4=BB=E5=8A=A8?= =?UTF-8?q?=E9=A1=B5=E3=80=81=E5=95=86=E5=93=81=E5=88=86=E7=B1=BB=E9=A1=B5?= =?UTF-8?q?=E7=9A=84=E7=8A=B6=E6=80=81=E4=B8=8E=E7=B1=BB=E5=9E=8B=E4=B8=BA?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E6=95=B0=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/repository/product_repository.go | 10 +++++----- internal/server/product_server.go | 14 ++++---------- scripts/sql/recreate-product-tables.sql | 6 +++--- 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 18624a8..473db80 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -480,7 +480,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C if err != nil { return err } - if root.NodeType != 0 || root.Level != 1 || root.ParentID != "" { + if root.NodeType != 1 || root.Level != 1 || root.ParentID != "" { return ErrCategoryTreeConflict } if tree.Category != nil { @@ -496,7 +496,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C if err != nil { return err } - if current.NodeType != 0 || current.Level != 2 || current.ParentID != tree.CategoryID { + if current.NodeType != 1 || current.Level != 2 || current.ParentID != tree.CategoryID { return ErrCategoryTreeConflict } if _, err := updateCategoryFields(ctx, tx, child); err != nil { @@ -1652,7 +1652,7 @@ SELECT id, status, version FROM product.product_category -WHERE node_type = 0 +WHERE node_type = 1 AND ($1 = false OR status = 1) ORDER BY level ASC, sort_num ASC, id ASC `, onlyVisible) @@ -1689,7 +1689,7 @@ SELECT id, status, version FROM product.product_category -WHERE node_type = 1 +WHERE node_type = 2 AND ($1 = false OR status = 1) ORDER BY sort_num ASC, id ASC `, onlyVisible) @@ -2625,7 +2625,7 @@ func statusFromDB(status int16) productv1.ProductStatus { case 3: return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE default: - return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED + return productv1.ProductStatus_PRODUCT_STATUS_NOT_FOUND } } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 6bca0a7..6dfde7b 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -32,8 +32,8 @@ const ( defaultPageSize = int32(20) maxPageSize = int32(100) - categoryNodeType = int32(0) - groupNodeType = int32(1) + categoryNodeType = int32(1) + groupNodeType = int32(2) defaultNodeStatus = int32(1) maxNodeNameLength = 100 @@ -991,9 +991,6 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P } statusValue := req.GetStatus() - if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { - statusValue = productv1.ProductStatus_PRODUCT_STATUS_INVENTORY - } if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && statusValue != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && statusValue != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { @@ -1266,9 +1263,6 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, name = derivedName } statusValue := sku.GetStatus() - if statusValue == 0 { - statusValue = 1 - } if statusValue < 0 || statusValue > 1 { return repository.SKURecord{}, errors.New("status must be 0 or 1") } @@ -1348,7 +1342,7 @@ func crossBorderJSONFromProto(info *productv1.CrossBorderInfo) (string, error) { return "", errors.New("cross_border_info.logistics_mode is invalid") } - marshalOptions := protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true} + marshalOptions := protojson.MarshalOptions{UseProtoNames: true, UseEnumNumbers: true, EmitUnpopulated: true} raw, err := marshalOptions.Marshal(info) if err != nil { return "", err @@ -1520,7 +1514,7 @@ func toProtoCartItemProduct(lineID string, record repository.CartItemProductReco LineId: lineID, ProductId: record.ProductID, SkuId: record.SKUID, - SpuStatus: productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED, + SpuStatus: productv1.ProductStatus_PRODUCT_STATUS_NOT_FOUND, } if record.Product == nil { return result diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index b777ebf..4079689 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -111,7 +111,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no CREATE TABLE IF NOT EXISTS product.product_category ( id BIGINT PRIMARY KEY, - node_type SMALLINT NOT NULL DEFAULT 0, + node_type SMALLINT NOT NULL DEFAULT 1, name VARCHAR(100) NOT NULL, parent_id BIGINT REFERENCES product.product_category(id), level SMALLINT NOT NULL, @@ -120,7 +120,7 @@ CREATE TABLE IF NOT EXISTS product.product_category ( status SMALLINT NOT NULL DEFAULT 1, version INTEGER NOT NULL DEFAULT 0, CONSTRAINT chk_product_category_node_type - CHECK (node_type IN (0, 1)), + CHECK (node_type IN (1, 2)), CONSTRAINT chk_product_category_level CHECK (level > 0), CONSTRAINT chk_product_category_status @@ -131,7 +131,7 @@ CREATE TABLE IF NOT EXISTS product.product_category ( COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组'; COMMENT ON COLUMN product.product_category.id IS '类别/分组节点主键'; -COMMENT ON COLUMN product.product_category.node_type IS '节点类型:0 分类,1 分组'; +COMMENT ON COLUMN product.product_category.node_type IS '节点类型:1 分类,2 分组'; COMMENT ON COLUMN product.product_category.name IS '节点展示名称'; COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3'; From e7fdf6cc190bf269a9af8b7c76dd9eb977240452 Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Thu, 13 Aug 2026 17:44:14 +0800 Subject: [PATCH 34/44] =?UTF-8?q?feat(product):=20=E5=88=86=E7=B1=BB?= =?UTF-8?q?=E5=95=86=E5=93=81=E5=88=97=E8=A1=A8=E8=BF=94=E5=9B=9E=E5=BA=93?= =?UTF-8?q?=E5=AD=98=E6=B1=87=E6=80=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/repository/product_repository.go | 38 +++++++++++++++-------- internal/server/product_server.go | 20 ++++++------ 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 473db80..f69b037 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -195,15 +195,17 @@ type ProductStatusUpdate struct { // CategoryProductRecord is the product summary returned by product list endpoints. type CategoryProductRecord struct { - ID string - SPUNo string - Title string - Status productv1.ProductStatus - ImageIDs []string - Price int64 - SoldQuantity int64 - CreatedAt time.Time - UpdatedAt time.Time + ID string + SPUNo string + Title string + Status productv1.ProductStatus + ImageIDs []string + Price int64 + SoldQuantity int64 + AvailableQuantity int64 + LockedQuantity int64 + CreatedAt time.Time + UpdatedAt time.Time } // CategoryRecord is the persistence model for product.product_category. @@ -1505,11 +1507,15 @@ SELECT p.updated_at, p.status, COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(sku_summary.price, 0), - COALESCE(sku_summary.sold_quantity, 0) + COALESCE(sku_summary.sold_quantity, 0), + COALESCE(sku_summary.available_quantity, 0), + COALESCE(sku_summary.locked_quantity, 0) FROM product.products p LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, - SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity + SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, + SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, + SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id WHERE pi.product_id = p.id @@ -1602,12 +1608,16 @@ SELECT p.updated_at, p.status, COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(sku_summary.price, 0), - COALESCE(sku_summary.sold_quantity, 0) + COALESCE(sku_summary.sold_quantity, 0), + COALESCE(sku_summary.available_quantity, 0), + COALESCE(sku_summary.locked_quantity, 0) FROM product.products p JOIN product.product_category_bindings b ON b.product_id = p.id LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, - SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity + SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, + SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, + SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id WHERE pi.product_id = p.id @@ -2207,6 +2217,8 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { &imageIDsJSON, &rec.Price, &rec.SoldQuantity, + &rec.AvailableQuantity, + &rec.LockedQuantity, ); err != nil { return nil, fmt.Errorf("scan category product: %w", err) } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 6dfde7b..a8c1972 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -1543,15 +1543,17 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv return nil } return &productv1.CategoryProduct{ - UpdatedAt: timeToMillisString(product.UpdatedAt), - CreatedAt: timeToMillisString(product.CreatedAt), - Title: product.Title, - ProductId: product.ID, - SpuNo: product.SPUNo, - Status: product.Status, - ImageIds: product.ImageIDs, - Price: product.Price, - SoldQuantity: product.SoldQuantity, + UpdatedAt: timeToMillisString(product.UpdatedAt), + CreatedAt: timeToMillisString(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Price: product.Price, + SoldQuantity: product.SoldQuantity, + AvailableQuantity: product.AvailableQuantity, + LockedQuantity: product.LockedQuantity, } } From 891bae474293297eff687e568ce90f83e13242d4 Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Fri, 14 Aug 2026 17:08:14 +0800 Subject: [PATCH 35/44] =?UTF-8?q?feat(product):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=95=86=E5=93=81=E5=A4=9A=E5=8F=B6=E5=AD=90=E5=88=86=E7=B1=BB?= =?UTF-8?q?=E4=B8=8E=E5=88=86=E7=B1=BB=E6=A0=91=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +- internal/repository/product_repository.go | 266 +++++++++++++++++++++- internal/server/product_server.go | 160 ++++++++++++- 3 files changed, 415 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 28fb70f..65a11ef 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `product_id` | 服务内 Snowflake 生成 | `product.products.id` | | `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` | | `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` | -| 分类绑定 ID | 传入 `leaf_category_id` 时服务内 Snowflake 生成 | `product.product_category_bindings.id` | +| 分类绑定 ID | 每个 `leaf_category_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` | 常用请求字段: @@ -54,7 +54,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `spu_no` | 是 | 商品业务编码,未删除商品内唯一 | | `title` | 是 | 商品标题 | | `selling_point` | 否 | 商品卖点 | -| `leaf_category_id` | 否 | 已存在的分类/分组节点 ID;传入后会写入分类绑定 | +| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 | | `image_ids` | 否 | 商品图片 ID 列表 | | `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID | | `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`OFF_SALE` | @@ -72,7 +72,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 "spu_no": "SPU202607100001", "title": "澳洲和牛家庭装", "selling_point": "原切谷饲,冷链到家", - "leaf_category_id": "726390485721088000", + "leaf_category_ids": ["726390485721088000"], "skus": [ { "sku_no": "SKU20260710000101", diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index f69b037..e15f849 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -22,6 +22,7 @@ var ErrProductNotFound = errors.New("product not found") var ErrCategoryNodeNotFound = errors.New("category or group node not found") var ErrCategoryVersionConflict = errors.New("category version conflict") var ErrCategoryTreeConflict = errors.New("category tree conflict") +var ErrInvalidLeafCategory = errors.New("category must be an existing second-level category") // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") @@ -68,8 +69,8 @@ type ProductRecord struct { FreightTemplateID string SaleTimeType int32 ScheduledSaleTime *time.Time - LeafCategoryID string - CategoryBindingID string + LeafCategoryIDs []string + CategoryBindingIDs []string Version int32 DeletedAt *time.Time CreatedAt time.Time @@ -174,6 +175,19 @@ type ProductUpdateInput struct { Product ProductRecord ExpectedVersion int32 SKUChange *SKUChange + // LeafCategoryIDs is nil when category bindings must remain unchanged. A + // non-nil empty slice clears all leaf-category bindings. + LeafCategoryIDs *[]string + CategoryBindingIDs []string +} + +// CategoryDeleteResult summarizes a destructive category deletion. +type CategoryDeleteResult struct { + DeletedCategoryID string + DeletedLevel int32 + DeletedCategoryCount int32 + UnboundProductCount int64 + UnboundBindingCount int64 } // SKUChangeResult records the SKU IDs affected by a product update. @@ -233,9 +247,10 @@ type CategoryFieldUpdate struct { // CategoryTreeUpdate groups an optional root update with direct-child updates. type CategoryTreeUpdate struct { - CategoryID string - Category *CategoryFieldUpdate - Children []CategoryFieldUpdate + CategoryID string + Category *CategoryFieldUpdate + Children []CategoryFieldUpdate + NewChildren []CategoryRecord } // ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. @@ -401,8 +416,8 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P createdSKUs = append(createdSKUs, *createdSKU) } - if product.LeafCategoryID != "" { - if err := insertCategoryBinding(ctx, tx, product.CategoryBindingID, createdProduct.ID, product.LeafCategoryID); err != nil { + if len(product.LeafCategoryIDs) > 0 { + if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs); err != nil { return nil, nil, err } } @@ -505,6 +520,14 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C return err } } + for _, child := range tree.NewChildren { + child.NodeType = 1 + child.ParentID = tree.CategoryID + child.Level = 2 + if _, err := insertCategoryNode(ctx, tx, child); err != nil { + return err + } + } } if err := tx.Commit(); err != nil { return fmt.Errorf("commit update category trees: %w", err) @@ -512,6 +535,112 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C return nil } +// DeleteCategory removes a leaf category or a complete top-level category tree +// and all affected product bindings in one transaction. Product rows and group +// bindings are deliberately retained. +func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32) (*CategoryDeleteResult, error) { + if expectedVersion < 0 { + return nil, errors.New("expected_version must be non-negative") + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin delete category: %w", err) + } + defer tx.Rollback() + + target, err := loadCategoryForUpdate(ctx, tx, categoryID) + if err != nil { + return nil, err + } + if target.NodeType != 1 || (target.Level != 1 && target.Level != 2) { + return nil, ErrCategoryTreeConflict + } + if target.Version != expectedVersion { + return nil, ErrCategoryVersionConflict + } + + categoryIDs := []int64{} + targetID, err := parseID(target.ID, "category_id") + if err != nil { + return nil, err + } + if target.Level == 1 { + rows, err := tx.QueryContext(ctx, ` +SELECT id, node_type, name, parent_id, level, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version +FROM product.product_category +WHERE parent_id = $1 +FOR UPDATE +`, targetID) + if err != nil { + return nil, fmt.Errorf("load category children for delete: %w", err) + } + for rows.Next() { + child, err := scanCategory(rows) + if err != nil { + rows.Close() + return nil, err + } + if child.NodeType != 1 || child.Level != 2 || child.ParentID != target.ID { + rows.Close() + return nil, ErrCategoryTreeConflict + } + childID, err := parseID(child.ID, "category_id") + if err != nil { + rows.Close() + return nil, err + } + categoryIDs = append(categoryIDs, childID) + } + if err := rows.Err(); err != nil { + rows.Close() + return nil, fmt.Errorf("iterate category children for delete: %w", err) + } + if err := rows.Close(); err != nil { + return nil, fmt.Errorf("close category children for delete: %w", err) + } + } + categoryIDs = append(categoryIDs, targetID) + placeholders := make([]string, len(categoryIDs)) + args := make([]any, len(categoryIDs)) + for index, id := range categoryIDs { + placeholders[index] = fmt.Sprintf("$%d", index+1) + args[index] = id + } + whereIDs := strings.Join(placeholders, ", ") + + result := &CategoryDeleteResult{ + DeletedCategoryID: target.ID, + DeletedLevel: target.Level, + DeletedCategoryCount: int32(len(categoryIDs)), + } + if err := tx.QueryRowContext(ctx, fmt.Sprintf(` +SELECT COUNT(DISTINCT product_id), COUNT(*) +FROM product.product_category_bindings +WHERE category_id IN (%s) +`, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil { + return nil, fmt.Errorf("count category bindings for delete: %w", err) + } + if _, err := tx.ExecContext(ctx, fmt.Sprintf(` +DELETE FROM product.product_category_bindings +WHERE category_id IN (%s) +`, whereIDs), args...); err != nil { + return nil, fmt.Errorf("delete category bindings: %w", err) + } + if target.Level == 1 { + if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE parent_id = $1`, targetID); err != nil { + return nil, fmt.Errorf("delete child categories: %w", err) + } + } + if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE id = $1`, targetID); err != nil { + return nil, fmt.Errorf("delete category: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit delete category: %w", err) + } + return result, nil +} + func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string) (*CategoryRecord, error) { id, err := parseID(categoryID, "category_id") if err != nil { @@ -833,6 +962,11 @@ FOR UPDATE if currentVersion != input.ExpectedVersion { return nil, ErrProductVersionConflict } + if input.LeafCategoryIDs != nil { + if err := replaceProductLeafCategoryBindings(ctx, tx, input.Product.ID, *input.LeafCategoryIDs, input.CategoryBindingIDs); err != nil { + return nil, err + } + } if input.SKUChange != nil && input.SKUChange.Mode == SKUChangeModeReplaceAll && statusFromDB(currentStatus) == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE { return nil, ErrSKUReplacementRequiresNotOnSale @@ -907,6 +1041,87 @@ WHERE id = $1 AND version = $17 AND deleted_at IS NULL return result, nil } +func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, leafCategoryIDs []string, bindingIDs []string) error { + if len(leafCategoryIDs) != len(bindingIDs) { + return errors.New("leaf category ids and category binding ids must have the same length") + } + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return err + } + parsedLeafCategoryIDs := make([]int64, len(leafCategoryIDs)) + seenCategoryIDs := make(map[int64]struct{}, len(leafCategoryIDs)) + for index, categoryID := range leafCategoryIDs { + parsedLeafCategoryIDs[index], err = parseID(categoryID, "leaf_category_id") + if err != nil { + return err + } + if _, duplicate := seenCategoryIDs[parsedLeafCategoryIDs[index]]; duplicate { + return errors.New("leaf_category_ids must not contain duplicates") + } + seenCategoryIDs[parsedLeafCategoryIDs[index]] = struct{}{} + if _, err := parseID(bindingIDs[index], "category binding id"); err != nil { + return err + } + } + + if len(parsedLeafCategoryIDs) > 0 { + placeholders := make([]string, len(parsedLeafCategoryIDs)) + args := make([]any, len(parsedLeafCategoryIDs)) + for index, categoryID := range parsedLeafCategoryIDs { + placeholders[index] = fmt.Sprintf("$%d", index+1) + args[index] = categoryID + } + rows, err := tx.QueryContext(ctx, fmt.Sprintf(` +SELECT id +FROM product.product_category +WHERE node_type = 1 + AND level = 2 + AND id IN (%s) +FOR KEY SHARE +`, strings.Join(placeholders, ", ")), args...) + if err != nil { + return fmt.Errorf("validate leaf categories: %w", err) + } + found := make(map[int64]struct{}, len(parsedLeafCategoryIDs)) + for rows.Next() { + var categoryID int64 + if err := rows.Scan(&categoryID); err != nil { + rows.Close() + return fmt.Errorf("scan leaf category: %w", err) + } + found[categoryID] = struct{}{} + } + if err := rows.Err(); err != nil { + rows.Close() + return fmt.Errorf("iterate leaf categories: %w", err) + } + if err := rows.Close(); err != nil { + return fmt.Errorf("close leaf categories: %w", err) + } + if len(found) != len(parsedLeafCategoryIDs) { + return ErrInvalidLeafCategory + } + } + + if _, err := tx.ExecContext(ctx, ` +DELETE FROM product.product_category_bindings AS b +USING product.product_category AS c +WHERE b.product_id = $1 + AND b.category_id = c.id + AND c.node_type = 1 + AND c.level = 2 +`, parsedProductID); err != nil { + return fmt.Errorf("delete product leaf category bindings: %w", err) + } + for index, categoryID := range leafCategoryIDs { + if err := insertCategoryBinding(ctx, tx, bindingIDs[index], productID, categoryID); err != nil { + return err + } + } + return nil +} + // UpdateProductStatus changes the product lifecycle state using optimistic locking. func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32) (*ProductStatusUpdate, error) { if expectedVersion < 0 { @@ -1412,10 +1627,47 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* if err != nil { return nil, nil, err } + leafCategoryIDs, err := r.listProductLeafCategoryIDs(ctx, productID) + if err != nil { + return nil, nil, err + } + product.LeafCategoryIDs = leafCategoryIDs return product, skus[productID], nil } +func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string) ([]string, error) { + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return nil, err + } + rows, err := r.db.QueryContext(ctx, ` +SELECT c.id +FROM product.product_category_bindings AS b +JOIN product.product_category AS c ON c.id = b.category_id +WHERE b.product_id = $1 + AND c.node_type = 1 + AND c.level = 2 +ORDER BY c.sort_num, c.id +`, parsedProductID) + if err != nil { + return nil, fmt.Errorf("list product leaf category ids: %w", err) + } + defer rows.Close() + leafCategoryIDs := make([]string, 0) + for rows.Next() { + var categoryID int64 + if err := rows.Scan(&categoryID); err != nil { + return nil, fmt.Errorf("scan product leaf category id: %w", err) + } + leafCategoryIDs = append(leafCategoryIDs, formatID(categoryID)) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate product leaf category ids: %w", err) + } + return leafCategoryIDs, nil +} + // BatchGetCartItemProducts loads current catalog facts for cart lines in request order. // It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable. func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup) ([]CartItemProductRecord, error) { diff --git a/internal/server/product_server.go b/internal/server/product_server.go index a8c1972..773c473 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -85,8 +85,8 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create skus[i].ID = s.idgen.NextString() skus[i].Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()} } - if product.LeafCategoryID != "" { - product.CategoryBindingID = s.idgen.NextString() + for range product.LeafCategoryIDs { + product.CategoryBindingIDs = append(product.CategoryBindingIDs, s.idgen.NextString()) } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( @@ -103,6 +103,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create if errors.Is(err, repository.ErrDuplicateSPUNo) { return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo) } + if errors.Is(err, repository.ErrInvalidLeafCategory) { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } return nil, status.Errorf(codes.Internal, "create product: %v", err) } observability.IncProductsCreated() @@ -253,10 +256,23 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() + var leafCategoryIDs *[]string + var categoryBindingIDs []string + if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_category_ids") { + leafCategoryIDs = &merged.LeafCategoryIDs + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + for range merged.LeafCategoryIDs { + categoryBindingIDs = append(categoryBindingIDs, s.idgen.NextString()) + } + } result, err := s.repo.UpdateProductWithSKUChange(dbCtx, repository.ProductUpdateInput{ - Product: merged, - ExpectedVersion: req.GetExpectedVersion(), - SKUChange: skuChange, + Product: merged, + ExpectedVersion: req.GetExpectedVersion(), + SKUChange: skuChange, + LeafCategoryIDs: leafCategoryIDs, + CategoryBindingIDs: categoryBindingIDs, }) if err != nil { dbSpan.RecordError(err) @@ -270,6 +286,8 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update return nil, status.Error(codes.FailedPrecondition, err.Error()) case errors.Is(err, repository.ErrSKUNotFound), errors.Is(err, repository.ErrSKUArchived): return nil, status.Error(codes.NotFound, err.Error()) + case errors.Is(err, repository.ErrInvalidLeafCategory): + return nil, status.Error(codes.InvalidArgument, err.Error()) default: s.observer.Logger(ctx).Error("update product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "update product: %v", err) @@ -506,6 +524,14 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1. if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } + for updateIndex := range updates { + for childIndex := range updates[updateIndex].NewChildren { + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + updates[updateIndex].NewChildren[childIndex].ID = s.idgen.NextString() + } + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates)))) defer dbSpan.End() if err := s.repo.UpdateCategoryTrees(dbCtx, updates); err != nil { @@ -542,6 +568,46 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1. return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil } +// DeleteCategory removes a single second-level category or a full top-level +// category tree. It never deletes products themselves. +func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.DeleteCategoryRequest) (*productv1.DeleteCategoryResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + categoryID, err := normalizeCategoryID(req.GetCategoryId(), "category_id") + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.GetExpectedVersion() < 0 { + return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") + } + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category.delete", trace.WithAttributes(attribute.String("category.id", categoryID))) + defer dbSpan.End() + result, err := s.repo.DeleteCategory(dbCtx, categoryID, req.GetExpectedVersion()) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrCategoryNodeNotFound): + return nil, status.Error(codes.NotFound, "category not found") + case errors.Is(err, repository.ErrCategoryVersionConflict): + return nil, status.Error(codes.Aborted, "category version conflict") + case errors.Is(err, repository.ErrCategoryTreeConflict): + return nil, status.Error(codes.FailedPrecondition, "target is not a deletable product category") + default: + s.observer.Logger(ctx).Error("delete category failed", zap.String("category_id", categoryID), zap.Error(err)) + return nil, status.Error(codes.Internal, "delete category") + } + } + return &productv1.DeleteCategoryResponse{ + DeletedCategoryId: result.DeletedCategoryID, + DeletedLevel: result.DeletedLevel, + DeletedCategoryCount: result.DeletedCategoryCount, + UnboundProductCount: result.UnboundProductCount, + UnboundBindingCount: result.UnboundBindingCount, + }, nil +} + // CreateGroup creates a top-level product group. func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) { if req == nil { @@ -844,7 +910,22 @@ func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ( } update.Children = append(update.Children, *patch) } - if update.Category == nil && len(update.Children) == 0 { + newChildNames := make(map[string]struct{}, len(tree.GetNewChildCategories())) + for _, child := range tree.GetNewChildCategories() { + if child == nil { + return nil, nil, errors.New("new_child_categories item is required") + } + newChild, err := newChildCategoryFromProto(child) + if err != nil { + return nil, nil, err + } + if _, exists := newChildNames[newChild.Name]; exists { + return nil, nil, errors.New("new_child_categories.name must be unique") + } + newChildNames[newChild.Name] = struct{}{} + update.NewChildren = append(update.NewChildren, newChild) + } + if update.Category == nil && len(update.Children) == 0 && len(update.NewChildren) == 0 { return nil, nil, errors.New("category tree patch must update category or child_categories") } sort.Slice(update.Children, func(i, j int) bool { return update.Children[i].ID < update.Children[j].ID }) @@ -856,6 +937,28 @@ func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ( return updates, rootIDs, nil } +func newChildCategoryFromProto(child *productv1.CreateChildCategory) (repository.CategoryRecord, error) { + name, err := normalizeNodeName(child.GetName(), "new_child_categories.name") + if err != nil { + return repository.CategoryRecord{}, err + } + imageIDs, err := normalizeNodeImageIDs(child.GetImageJson()) + if err != nil { + return repository.CategoryRecord{}, err + } + statusValue, err := normalizeNodeStatus(child.Status) + if err != nil { + return repository.CategoryRecord{}, err + } + return repository.CategoryRecord{ + NodeType: categoryNodeType, + Name: name, + ImageIDs: imageIDs, + SortNum: child.GetSortNum(), + Status: statusValue, + }, nil +} + func categoryFieldUpdateFromProto(id string, patch *productv1.CategoryFieldPatch, field string) (*repository.CategoryFieldUpdate, error) { if patch == nil { return nil, fmt.Errorf("%s is required", field) @@ -1019,8 +1122,12 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), - LeafCategoryID: strings.TrimSpace(req.GetLeafCategoryId()), } + leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCategoryIds()) + if err != nil { + return repository.ProductRecord{}, nil, err + } + record.LeafCategoryIDs = leafCategoryIDs if record.FreightFixedAmount < 0 { return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0") } @@ -1102,6 +1209,12 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime()) case "goods_type": merged.GoodsType = update.GetGoodsType() + case "leaf_category_ids": + leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCategoryIds()) + if err != nil { + return repository.ProductRecord{}, err + } + merged.LeafCategoryIDs = leafCategoryIDs default: return repository.ProductRecord{}, fmt.Errorf("unsupported update field %q", path) } @@ -1109,6 +1222,15 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro return merged, nil } +func containsUpdatePath(paths []string, target string) bool { + for _, path := range paths { + if path == target { + return true + } + } + return false +} + func validateProductForUpdate(product repository.ProductRecord) error { if strings.TrimSpace(product.Title) == "" { return errors.New("title is required") @@ -1382,6 +1504,29 @@ func normalizeStringList(values []string) []string { return out } +func normalizeLeafCategoryIDs(values []string) ([]string, error) { + if len(values) > 100 { + return nil, errors.New("leaf_category_ids must contain at most 100 items") + } + leafCategoryIDs := make([]string, 0, len(values)) + seen := make(map[string]struct{}, len(values)) + for _, value := range values { + categoryID := strings.TrimSpace(value) + if categoryID == "" { + return nil, errors.New("leaf_category_ids must not contain an empty id") + } + if _, err := normalizeCategoryID(categoryID, "leaf_category_ids"); err != nil { + return nil, err + } + if _, duplicate := seen[categoryID]; duplicate { + return nil, errors.New("leaf_category_ids must not contain duplicates") + } + seen[categoryID] = struct{}{} + leafCategoryIDs = append(leafCategoryIDs, categoryID) + } + return leafCategoryIDs, nil +} + func normalizeGroupProductIDs(values []string) ([]string, error) { productIDs := normalizeStringList(values) if len(productIDs) == 0 { @@ -1506,6 +1651,7 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), Version: product.Version, DeletedAt: timePtrToMillisString(product.DeletedAt), + LeafCategoryIds: append([]string(nil), product.LeafCategoryIDs...), } } From ba95c9079f53fa62de9a54877ddee3be88fa2c68 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Mon, 31 Aug 2026 15:01:56 +0800 Subject: [PATCH 36/44] feat(product): update product status handling and enhance category tree response logging --- internal/server/product_server.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 773c473..7701fe2 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -468,9 +468,16 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis dbSpan.SetAttributes(attribute.Int("category.result_count", len(categories))) observability.IncCategoryTreeLists() - return &productv1.ListCategoryTreeResponse{ + resp := &productv1.ListCategoryTreeResponse{ Categories: buildCategoryTree(categories), - }, nil + } + if payload, marshalErr := (protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true}).Marshal(resp); marshalErr != nil { + s.observer.Logger(ctx).Warn("marshal category tree response for logging failed", zap.Error(marshalErr)) + } else { + s.observer.Logger(ctx).Info("list category tree response", zap.ByteString("response", payload)) + } + + return resp, nil } // CreateCategoryTree creates a top-level category and optional second-level categories. @@ -1094,6 +1101,9 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P } statusValue := req.GetStatus() + if statusValue == productv1.ProductStatus_PRODUCT_STATUS_NOT_FOUND { + statusValue = productv1.ProductStatus_PRODUCT_STATUS_INVENTORY + } if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && statusValue != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && statusValue != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { From 71ca5b809f5b50f289bd7b7f5d6ac25a7a6e506a Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Mon, 31 Aug 2026 15:10:18 +0800 Subject: [PATCH 37/44] feat(product): add diagnostics for empty category tree responses and logging --- internal/repository/product_repository.go | 53 +++++++++++++++++++++++ internal/server/product_server.go | 45 +++++++++++++++++++ 2 files changed, 98 insertions(+) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index e15f849..cc1ce06 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -235,6 +235,22 @@ type CategoryRecord struct { Version int32 } +// CategoryTreeDiagnostics summarizes category rows when the storefront tree query is empty. +type CategoryTreeDiagnostics struct { + TotalRows int64 + MatchingRows int64 + ExpectedCategoryRows int64 + ExpectedVisibleRows int64 + ExpectedHiddenRows int64 + LegacyCategoryRows int64 + LegacyVisibleRows int64 + LegacyHiddenRows int64 + GroupRows int64 + GroupVisibleRows int64 + GroupHiddenRows int64 + OtherNodeTypeRows int64 +} + // CategoryFieldUpdate selects mutable fields of one category node. type CategoryFieldUpdate struct { ID string @@ -1938,6 +1954,43 @@ ORDER BY level ASC, sort_num ASC, id ASC return categories, nil } +// CategoryTreeDiagnostics loads aggregate counts used to explain an empty category tree response. +func (r *ProductRepository) CategoryTreeDiagnostics(ctx context.Context, onlyVisible bool) (*CategoryTreeDiagnostics, error) { + var stats CategoryTreeDiagnostics + if err := r.db.QueryRowContext(ctx, ` +SELECT + COUNT(*) AS total_rows, + COUNT(*) FILTER (WHERE node_type = 1 AND ($1 = false OR status = 1)) AS matching_rows, + COUNT(*) FILTER (WHERE node_type = 1) AS expected_category_rows, + COUNT(*) FILTER (WHERE node_type = 1 AND status = 1) AS expected_visible_rows, + COUNT(*) FILTER (WHERE node_type = 1 AND status = 0) AS expected_hidden_rows, + COUNT(*) FILTER (WHERE node_type = 0) AS legacy_category_rows, + COUNT(*) FILTER (WHERE node_type = 0 AND status = 1) AS legacy_visible_rows, + COUNT(*) FILTER (WHERE node_type = 0 AND status = 0) AS legacy_hidden_rows, + COUNT(*) FILTER (WHERE node_type = 2) AS group_rows, + COUNT(*) FILTER (WHERE node_type = 2 AND status = 1) AS group_visible_rows, + COUNT(*) FILTER (WHERE node_type = 2 AND status = 0) AS group_hidden_rows, + COUNT(*) FILTER (WHERE node_type NOT IN (0, 1, 2)) AS other_node_type_rows +FROM product.product_category +`, onlyVisible).Scan( + &stats.TotalRows, + &stats.MatchingRows, + &stats.ExpectedCategoryRows, + &stats.ExpectedVisibleRows, + &stats.ExpectedHiddenRows, + &stats.LegacyCategoryRows, + &stats.LegacyVisibleRows, + &stats.LegacyHiddenRows, + &stats.GroupRows, + &stats.GroupVisibleRows, + &stats.GroupHiddenRows, + &stats.OtherNodeTypeRows, + ); err != nil { + return nil, fmt.Errorf("query category tree diagnostics: %w", err) + } + return &stats, nil +} + // ListGroupNodes loads product group nodes. func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { rows, err := r.db.QueryContext(ctx, ` diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 7701fe2..aaa887f 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -466,6 +466,9 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis return nil, status.Errorf(codes.Internal, "list category tree: %v", err) } dbSpan.SetAttributes(attribute.Int("category.result_count", len(categories))) + if len(categories) == 0 { + s.logEmptyCategoryTreeReason(ctx, dbCtx, onlyVisible) + } observability.IncCategoryTreeLists() resp := &productv1.ListCategoryTreeResponse{ @@ -480,6 +483,48 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis return resp, nil } +func (s *ProductServer) logEmptyCategoryTreeReason(ctx context.Context, dbCtx context.Context, onlyVisible bool) { + stats, err := s.repo.CategoryTreeDiagnostics(dbCtx, onlyVisible) + if err != nil { + s.observer.Logger(ctx).Warn("category tree returned empty and diagnostics failed", + zap.Bool("only_visible", onlyVisible), + zap.Error(err), + ) + return + } + + reason := "no rows matched category tree query" + switch { + case stats.TotalRows == 0: + reason = "product.product_category has no rows" + case stats.ExpectedCategoryRows == 0 && stats.LegacyCategoryRows > 0: + reason = "category rows use legacy node_type=0 but query expects node_type=1" + case onlyVisible && stats.ExpectedCategoryRows > 0 && stats.ExpectedVisibleRows == 0: + reason = "only_visible=true filtered out all node_type=1 category rows because status is not 1" + case stats.ExpectedCategoryRows == 0 && stats.GroupRows > 0: + reason = "table has group rows but no node_type=1 category rows" + case stats.OtherNodeTypeRows > 0: + reason = "table rows use unsupported node_type values" + } + + s.observer.Logger(ctx).Info("category tree returned empty", + zap.String("reason", reason), + zap.Bool("only_visible", onlyVisible), + zap.Int64("total_rows", stats.TotalRows), + zap.Int64("matching_rows", stats.MatchingRows), + zap.Int64("expected_category_rows_node_type_1", stats.ExpectedCategoryRows), + zap.Int64("expected_visible_rows_node_type_1_status_1", stats.ExpectedVisibleRows), + zap.Int64("expected_hidden_rows_node_type_1_status_0", stats.ExpectedHiddenRows), + zap.Int64("legacy_category_rows_node_type_0", stats.LegacyCategoryRows), + zap.Int64("legacy_visible_rows_node_type_0_status_1", stats.LegacyVisibleRows), + zap.Int64("legacy_hidden_rows_node_type_0_status_0", stats.LegacyHiddenRows), + zap.Int64("group_rows_node_type_2", stats.GroupRows), + zap.Int64("group_visible_rows_node_type_2_status_1", stats.GroupVisibleRows), + zap.Int64("group_hidden_rows_node_type_2_status_0", stats.GroupHiddenRows), + zap.Int64("other_node_type_rows", stats.OtherNodeTypeRows), + ) +} + // 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 { From f48a3bce2e4050a7e2075fbc9d0bb09883672daa Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Mon, 31 Aug 2026 18:02:57 +0800 Subject: [PATCH 38/44] feat(product): remove CategoryTreeDiagnostics and related logging for empty category tree responses --- internal/repository/product_repository.go | 53 ----------------------- internal/server/product_server.go | 45 ------------------- 2 files changed, 98 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index cc1ce06..e15f849 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -235,22 +235,6 @@ type CategoryRecord struct { Version int32 } -// CategoryTreeDiagnostics summarizes category rows when the storefront tree query is empty. -type CategoryTreeDiagnostics struct { - TotalRows int64 - MatchingRows int64 - ExpectedCategoryRows int64 - ExpectedVisibleRows int64 - ExpectedHiddenRows int64 - LegacyCategoryRows int64 - LegacyVisibleRows int64 - LegacyHiddenRows int64 - GroupRows int64 - GroupVisibleRows int64 - GroupHiddenRows int64 - OtherNodeTypeRows int64 -} - // CategoryFieldUpdate selects mutable fields of one category node. type CategoryFieldUpdate struct { ID string @@ -1954,43 +1938,6 @@ ORDER BY level ASC, sort_num ASC, id ASC return categories, nil } -// CategoryTreeDiagnostics loads aggregate counts used to explain an empty category tree response. -func (r *ProductRepository) CategoryTreeDiagnostics(ctx context.Context, onlyVisible bool) (*CategoryTreeDiagnostics, error) { - var stats CategoryTreeDiagnostics - if err := r.db.QueryRowContext(ctx, ` -SELECT - COUNT(*) AS total_rows, - COUNT(*) FILTER (WHERE node_type = 1 AND ($1 = false OR status = 1)) AS matching_rows, - COUNT(*) FILTER (WHERE node_type = 1) AS expected_category_rows, - COUNT(*) FILTER (WHERE node_type = 1 AND status = 1) AS expected_visible_rows, - COUNT(*) FILTER (WHERE node_type = 1 AND status = 0) AS expected_hidden_rows, - COUNT(*) FILTER (WHERE node_type = 0) AS legacy_category_rows, - COUNT(*) FILTER (WHERE node_type = 0 AND status = 1) AS legacy_visible_rows, - COUNT(*) FILTER (WHERE node_type = 0 AND status = 0) AS legacy_hidden_rows, - COUNT(*) FILTER (WHERE node_type = 2) AS group_rows, - COUNT(*) FILTER (WHERE node_type = 2 AND status = 1) AS group_visible_rows, - COUNT(*) FILTER (WHERE node_type = 2 AND status = 0) AS group_hidden_rows, - COUNT(*) FILTER (WHERE node_type NOT IN (0, 1, 2)) AS other_node_type_rows -FROM product.product_category -`, onlyVisible).Scan( - &stats.TotalRows, - &stats.MatchingRows, - &stats.ExpectedCategoryRows, - &stats.ExpectedVisibleRows, - &stats.ExpectedHiddenRows, - &stats.LegacyCategoryRows, - &stats.LegacyVisibleRows, - &stats.LegacyHiddenRows, - &stats.GroupRows, - &stats.GroupVisibleRows, - &stats.GroupHiddenRows, - &stats.OtherNodeTypeRows, - ); err != nil { - return nil, fmt.Errorf("query category tree diagnostics: %w", err) - } - return &stats, nil -} - // ListGroupNodes loads product group nodes. func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { rows, err := r.db.QueryContext(ctx, ` diff --git a/internal/server/product_server.go b/internal/server/product_server.go index aaa887f..7701fe2 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -466,9 +466,6 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis return nil, status.Errorf(codes.Internal, "list category tree: %v", err) } dbSpan.SetAttributes(attribute.Int("category.result_count", len(categories))) - if len(categories) == 0 { - s.logEmptyCategoryTreeReason(ctx, dbCtx, onlyVisible) - } observability.IncCategoryTreeLists() resp := &productv1.ListCategoryTreeResponse{ @@ -483,48 +480,6 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis return resp, nil } -func (s *ProductServer) logEmptyCategoryTreeReason(ctx context.Context, dbCtx context.Context, onlyVisible bool) { - stats, err := s.repo.CategoryTreeDiagnostics(dbCtx, onlyVisible) - if err != nil { - s.observer.Logger(ctx).Warn("category tree returned empty and diagnostics failed", - zap.Bool("only_visible", onlyVisible), - zap.Error(err), - ) - return - } - - reason := "no rows matched category tree query" - switch { - case stats.TotalRows == 0: - reason = "product.product_category has no rows" - case stats.ExpectedCategoryRows == 0 && stats.LegacyCategoryRows > 0: - reason = "category rows use legacy node_type=0 but query expects node_type=1" - case onlyVisible && stats.ExpectedCategoryRows > 0 && stats.ExpectedVisibleRows == 0: - reason = "only_visible=true filtered out all node_type=1 category rows because status is not 1" - case stats.ExpectedCategoryRows == 0 && stats.GroupRows > 0: - reason = "table has group rows but no node_type=1 category rows" - case stats.OtherNodeTypeRows > 0: - reason = "table rows use unsupported node_type values" - } - - s.observer.Logger(ctx).Info("category tree returned empty", - zap.String("reason", reason), - zap.Bool("only_visible", onlyVisible), - zap.Int64("total_rows", stats.TotalRows), - zap.Int64("matching_rows", stats.MatchingRows), - zap.Int64("expected_category_rows_node_type_1", stats.ExpectedCategoryRows), - zap.Int64("expected_visible_rows_node_type_1_status_1", stats.ExpectedVisibleRows), - zap.Int64("expected_hidden_rows_node_type_1_status_0", stats.ExpectedHiddenRows), - zap.Int64("legacy_category_rows_node_type_0", stats.LegacyCategoryRows), - zap.Int64("legacy_visible_rows_node_type_0_status_1", stats.LegacyVisibleRows), - zap.Int64("legacy_hidden_rows_node_type_0_status_0", stats.LegacyHiddenRows), - zap.Int64("group_rows_node_type_2", stats.GroupRows), - zap.Int64("group_visible_rows_node_type_2_status_1", stats.GroupVisibleRows), - zap.Int64("group_hidden_rows_node_type_2_status_0", stats.GroupHiddenRows), - zap.Int64("other_node_type_rows", stats.OtherNodeTypeRows), - ) -} - // 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 { From cd60a19cdf0c74703df26e2673a35b734d5c9cc3 Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Tue, 1 Sep 2026 11:33:41 +0800 Subject: [PATCH 39/44] fix: adapt product status unspecified enum --- internal/repository/product_repository.go | 2 +- internal/server/product_server.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index e15f849..404909d 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -2889,7 +2889,7 @@ func statusFromDB(status int16) productv1.ProductStatus { case 3: return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE default: - return productv1.ProductStatus_PRODUCT_STATUS_NOT_FOUND + return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED } } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 7701fe2..e8d6747 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -1101,7 +1101,7 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P } statusValue := req.GetStatus() - if statusValue == productv1.ProductStatus_PRODUCT_STATUS_NOT_FOUND { + if statusValue == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED { statusValue = productv1.ProductStatus_PRODUCT_STATUS_INVENTORY } if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && @@ -1670,7 +1670,7 @@ func toProtoCartItemProduct(lineID string, record repository.CartItemProductReco LineId: lineID, ProductId: record.ProductID, SkuId: record.SKUID, - SpuStatus: productv1.ProductStatus_PRODUCT_STATUS_NOT_FOUND, + SpuStatus: productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED, } if record.Product == nil { return result From 50ef666baf36c4f4100bbca03e09f0312f47426e Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Wed, 2 Sep 2026 17:30:02 +0800 Subject: [PATCH 40/44] =?UTF-8?q?feat(product):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=89=8D=E5=8F=B0=E5=95=86=E5=93=81=E5=85=B3=E9=94=AE=E5=AD=97?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E8=83=BD=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + internal/observability/observability.go | 14 +++ internal/repository/product_repository.go | 99 +++++++++++++++++++ .../repository/product_repository_test.go | 10 ++ internal/server/product_server.go | 48 +++++++++ 5 files changed, 173 insertions(+) create mode 100644 internal/repository/product_repository_test.go diff --git a/README.md b/README.md index 65a11ef..f0d0882 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 | | `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 | | `ListProducts` | 分页返回全部未软删除商品列表 | Admin API | +| `SearchProducts` | 按标题关键字分页返回前台可见商品 | 小程序 / H5 BFF | | `UpdateProduct` | 更新 SPU 字段,并更新或替换 SKU 集合 | Admin API | | `UpdateProductStatus` | 显式变更仓库中、上架、已售罄状态 | Admin API | | `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 | @@ -27,6 +28,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 | | `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 | | `ListProducts` | `GET /v1/products?page=1&page_size=20` | `ListProductsRequest` | `ListProductsResponse` | 分页查询全部未软删除商品 | +| `SearchProducts` | gRPC only | `SearchProductsRequest` | `SearchProductsResponse` | 按标题关键字分页查询前台可见商品 | | `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU | | `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 | | `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 | diff --git a/internal/observability/observability.go b/internal/observability/observability.go index c4bebb5..f5bd91c 100644 --- a/internal/observability/observability.go +++ b/internal/observability/observability.go @@ -74,6 +74,15 @@ var ( }, ) + productSearchesTotal = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "product_searches_total", + Help: "Total number of successful storefront product keyword searches.", + }, + ) + categoryTreeListsTotal = promauto.NewCounter( prometheus.CounterOpts{ Namespace: "ids", @@ -223,6 +232,11 @@ func IncProductLists() { productListsTotal.Inc() } +// IncProductSearches records a successful storefront product keyword search. +func IncProductSearches() { + productSearchesTotal.Inc() +} + // IncCategoryTreeLists records a successful category tree query. func IncCategoryTreeLists() { categoryTreeListsTotal.Inc() diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 404909d..e0d3648 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -1797,6 +1797,93 @@ LIMIT $1 OFFSET $2 return products, total, nil } +// SearchProducts loads storefront-visible product summaries whose titles contain +// keyword. Callers cannot opt out of the visibility predicate: soft-deleted and +// inventory-only products must never be exposed by keyword search. +func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + + escapedKeyword := escapeLikeLiteral(keyword) + containsPattern := "%" + escapedKeyword + "%" + prefixPattern := escapedKeyword + "%" + onSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE) + offSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE) + + var total int64 + if err := r.db.QueryRowContext(ctx, ` +SELECT COUNT(*) +FROM product.products p +WHERE p.deleted_at IS NULL + AND p.status IN ($2, $3) + AND p.title ILIKE $1 ESCAPE '\' +`, containsPattern, onSaleStatus, offSaleStatus).Scan(&total); err != nil { + return nil, 0, fmt.Errorf("count searched products: %w", err) + } + if total == 0 { + return []*CategoryProductRecord{}, 0, nil + } + + offset := int64(page-1) * int64(pageSize) + rows, err := r.db.QueryContext(ctx, ` +SELECT p.updated_at, + p.created_at, + p.title, + p.id, + p.spu_no, + p.status, + COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(sku_summary.price, 0), + COALESCE(sku_summary.sold_quantity, 0), + COALESCE(sku_summary.available_quantity, 0), + COALESCE(sku_summary.locked_quantity, 0) +FROM product.products p +LEFT JOIN LATERAL ( + SELECT MIN(pi.price) AS price, + SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, + SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, + SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity + FROM product.product_items pi + LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE +) sku_summary ON TRUE +WHERE p.deleted_at IS NULL + AND p.status IN ($2, $3) + AND p.title ILIKE $1 ESCAPE '\' +ORDER BY CASE + WHEN LOWER(p.title) = LOWER($4) THEN 0 + WHEN p.title ILIKE $5 ESCAPE '\' THEN 1 + ELSE 2 + END, + p.updated_at DESC, + p.id DESC +LIMIT $6 OFFSET $7 +`, containsPattern, onSaleStatus, offSaleStatus, keyword, prefixPattern, pageSize, offset) + if err != nil { + return nil, 0, fmt.Errorf("query searched products: %w", err) + } + defer rows.Close() + + products := make([]*CategoryProductRecord, 0, pageSize) + for rows.Next() { + product, err := scanCategoryProduct(rows) + if err != nil { + return nil, 0, err + } + products = append(products, product) + } + if err := rows.Err(); err != nil { + return nil, 0, fmt.Errorf("iterate searched products: %w", err) + } + return products, total, nil +} + // CountProducts returns aggregate product counts grouped by lifecycle status. func (r *ProductRepository) CountProducts(ctx context.Context) (*ProductCountRecord, error) { var counts ProductCountRecord @@ -2893,6 +2980,18 @@ func statusFromDB(status int16) productv1.ProductStatus { } } +// escapeLikeLiteral makes PostgreSQL LIKE metacharacters literal. The caller +// still passes the resulting value as a bound query parameter; this helper is +// about preserving search semantics rather than SQL injection prevention. +func escapeLikeLiteral(value string) string { + replacer := strings.NewReplacer( + `\`, `\\`, + `%`, `\%`, + `_`, `\_`, + ) + return replacer.Replace(value) +} + func parseID(raw, field string) (int64, error) { id, err := strconv.ParseInt(raw, 10, 64) if err != nil || id <= 0 { diff --git a/internal/repository/product_repository_test.go b/internal/repository/product_repository_test.go new file mode 100644 index 0000000..7ebc161 --- /dev/null +++ b/internal/repository/product_repository_test.go @@ -0,0 +1,10 @@ +package repository + +import "testing" + +func TestEscapeLikeLiteral(t *testing.T) { + input := `100%_off\\bundle` + if got, want := escapeLikeLiteral(input), `100\%\_off\\\\bundle`; got != want { + t.Fatalf("escapeLikeLiteral(%q) = %q, want %q", input, got, want) + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index e8d6747..dfa2cbf 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -10,6 +10,7 @@ import ( "strconv" "strings" "time" + "unicode/utf8" "go.opentelemetry.io/otel/attribute" otelcodes "go.opentelemetry.io/otel/codes" @@ -39,6 +40,7 @@ const ( maxNodeNameLength = 100 maxProductsPerGroupRequest = 100 maxCartItemProductBatchSize = 100 + maxSearchKeywordLength = 50 ) // ProductServer implements productv1.ProductServiceServer. @@ -367,6 +369,52 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro }, nil } +// SearchProducts returns storefront-visible products whose titles contain the +// supplied keyword. Visibility is enforced inside the repository and cannot be +// relaxed by callers. +func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.SearchProductsRequest) (*productv1.SearchProductsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + + keyword := strings.TrimSpace(req.GetKeyword()) + keywordLength := utf8.RuneCountInString(keyword) + if keyword == "" || keywordLength > maxSearchKeywordLength { + return nil, status.Errorf(codes.InvalidArgument, "keyword must contain between 1 and %d characters", maxSearchKeywordLength) + } + page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.search", trace.WithAttributes( + attribute.Int("keyword.length", keywordLength), + attribute.Int("page", int(page)), + attribute.Int("page_size", int(pageSize)), + )) + defer dbSpan.End() + + products, total, err := s.repo.SearchProducts(dbCtx, keyword, page, pageSize) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("search products failed", zap.Int("keyword_length", keywordLength), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "search products: %v", err) + } + dbSpan.SetAttributes(attribute.Int64("product.total", total), attribute.Int("product.result_count", len(products))) + observability.IncProductSearches() + + protoProducts := make([]*productv1.CategoryProduct, 0, len(products)) + for _, product := range products { + protoProducts = append(protoProducts, toProtoCategoryProduct(product)) + } + + return &productv1.SearchProductsResponse{ + Products: protoProducts, + Page: page, + PageSize: pageSize, + Total: total, + TotalPages: totalPages(total, pageSize), + }, nil +} + // ListCategoryProducts returns a paginated product list under a category. func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { if req == nil || req.GetCategoryId() == "" { From c41ca76a2ad5501dd04c98a55e0124507a42582c Mon Sep 17 00:00:00 2001 From: BXY <103352887+BXY0414@users.noreply.github.com> Date: Wed, 2 Sep 2026 18:58:45 +0800 Subject: [PATCH 41/44] =?UTF-8?q?refactor(product):=20=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=A4=8D=E7=94=A8=E5=88=86=E7=B1=BB=E5=95=86?= =?UTF-8?q?=E5=93=81=E5=88=97=E8=A1=A8=E5=93=8D=E5=BA=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- internal/server/product_server.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f0d0882..9979161 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 | | `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 | | `ListProducts` | `GET /v1/products?page=1&page_size=20` | `ListProductsRequest` | `ListProductsResponse` | 分页查询全部未软删除商品 | -| `SearchProducts` | gRPC only | `SearchProductsRequest` | `SearchProductsResponse` | 按标题关键字分页查询前台可见商品 | +| `SearchProducts` | gRPC only | `SearchProductsRequest` | `ListCategoryProductsResponse` | 按标题关键字分页查询前台可见商品,响应与分类商品列表一致 | | `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU | | `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 | | `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 | diff --git a/internal/server/product_server.go b/internal/server/product_server.go index dfa2cbf..2f39886 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -372,7 +372,7 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro // SearchProducts returns storefront-visible products whose titles contain the // supplied keyword. Visibility is enforced inside the repository and cannot be // relaxed by callers. -func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.SearchProductsRequest) (*productv1.SearchProductsResponse, error) { +func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.SearchProductsRequest) (*productv1.ListCategoryProductsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } @@ -406,7 +406,7 @@ func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.Searc protoProducts = append(protoProducts, toProtoCategoryProduct(product)) } - return &productv1.SearchProductsResponse{ + return &productv1.ListCategoryProductsResponse{ Products: protoProducts, Page: page, PageSize: pageSize, From e2df9fd2e7f78b4a9806e34d6134d3a966dd401c Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Sat, 5 Sep 2026 00:05:50 +0800 Subject: [PATCH 42/44] feat(product): add GetProductBySKU method and corresponding server handler with validation --- internal/repository/product_repository.go | 21 ++++++++++++++ internal/server/get_product_by_sku_test.go | 19 +++++++++++++ internal/server/product_server.go | 33 ++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 internal/server/get_product_by_sku_test.go diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index e0d3648..e7c023d 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -1636,6 +1636,27 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* return product, skus[productID], nil } +// GetProductBySKU loads the SPU that owns skuID (product_items.id is the SKU PK). +func (r *ProductRepository) GetProductBySKU(ctx context.Context, skuID string) (*ProductRecord, []SKURecord, error) { + parsedSKU, err := parseID(skuID, "sku_id") + if err != nil { + return nil, nil, err + } + var productID int64 + err = r.db.QueryRowContext(ctx, ` +SELECT product_id +FROM product.product_items +WHERE id = $1 AND deleted_at IS NULL AND is_archived = FALSE +`, parsedSKU).Scan(&productID) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil, ErrSKUNotFound + } + if err != nil { + return nil, nil, fmt.Errorf("lookup product by sku: %w", err) + } + return r.GetProduct(ctx, formatID(productID)) +} + func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string) ([]string, error) { parsedProductID, err := parseID(productID, "product_id") if err != nil { diff --git a/internal/server/get_product_by_sku_test.go b/internal/server/get_product_by_sku_test.go new file mode 100644 index 0000000..338ce32 --- /dev/null +++ b/internal/server/get_product_by_sku_test.go @@ -0,0 +1,19 @@ +package server + +import ( + "context" + "testing" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" +) + +func TestGetProductBySkuRequiresID(t *testing.T) { + s := NewProductServer(nil, nil, nil, nil) + _, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{}) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 2f39886..9215a0e 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -157,6 +157,39 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc }, nil } +// GetProductBySku returns the SPU that owns the SKU. +func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetProductBySkuRequest) (*productv1.GetProductResponse, error) { + if req == nil || req.GetSkuId() == "" { + return nil, status.Error(codes.InvalidArgument, "sku_id is required") + } + if err := validatePositiveID(req.GetSkuId(), "sku_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load_by_sku", trace.WithAttributes(attribute.String("sku.id", req.GetSkuId()))) + defer dbSpan.End() + + product, skus, err := s.repo.GetProductBySKU(dbCtx, req.GetSkuId()) + if errors.Is(err, repository.ErrSKUNotFound) { + dbSpan.SetStatus(otelcodes.Error, "sku not found") + return nil, status.Error(codes.NotFound, "sku not found") + } + if errors.Is(err, repository.ErrProductNotFound) { + dbSpan.SetStatus(otelcodes.Error, "product not found") + return nil, status.Error(codes.NotFound, "product not found") + } + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("get product by sku failed", zap.String("sku_id", req.GetSkuId()), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "get product by sku: %v", err) + } + + return &productv1.GetProductResponse{ + Product: toProtoProduct(product, skus), + }, nil +} + // BatchGetCartItemProduct returns current SPU/SKU facts for cart rows in request order. // Missing and soft-deleted records are represented by their default invalid state rather // than failing the whole batch; malformed requests still return InvalidArgument. From bfdbe0361dd9cd8cc9b60d55082526a16bfa2b4a Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Sat, 5 Sep 2026 13:49:11 +0800 Subject: [PATCH 43/44] refactor(product): rename available_quantity to stock_quantity across the codebase --- README.md | 2 +- docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md | 14 +- internal/repository/product_repository.go | 178 +++++++++--------- internal/server/product_server.go | 124 ++++++------ scripts/sql/recreate-product-tables.sql | 6 +- .../sql/rename-inventory-stock-quantity.sql | 5 + 6 files changed, 167 insertions(+), 162 deletions(-) create mode 100644 scripts/sql/rename-inventory-stock-quantity.sql diff --git a/README.md b/README.md index 9979161..1e2b911 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 { "sku_no": "SKU20260710000101", "price": 12800, - "available_quantity": 100, + "stock_quantity": 100, "k1": "规格", "v1": "1kg" } diff --git a/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md b/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md index 226bc89..6b56fee 100644 --- a/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md +++ b/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md @@ -40,7 +40,7 @@ INVENTORY -> ON_SALE 运营人员上架;至少存在一个可售 SKU。 ON_SALE -> OFF_SALE - 所有当前可售 SKU 的 available_quantity - locked_quantity <= 0 时系统自动下架, + 所有当前可售 SKU 的 stock_quantity - locked_quantity <= 0 时系统自动下架, 或由运营人员主动下架。 OFF_SALE -> ON_SALE @@ -111,7 +111,7 @@ Content-Type: application/json "expected_inventory_version": 8, "name": "红色 M 码", "price": 9900, - "available_quantity": 50, + "stock_quantity": 50, "status": 1, "image_ids": ["726390485721088011"] } @@ -136,11 +136,11 @@ Content-Type: application/json - `price`; - `name`; -- `available_quantity`; +- `stock_quantity`; - `status`; - `image_ids`。 -不能修改 `sku_no`、`k1/v1` 至 `k3/v3`、销量或锁定库存。`name` 可单独覆盖,不影响 SKU 编号和规格组合。`available_quantity` 是更新后的绝对数量,且不得小于 `locked_quantity`。 +不能修改 `sku_no`、`k1/v1` 至 `k3/v3`、销量或锁定库存。`name` 可单独覆盖,不影响 SKU 编号和规格组合。`stock_quantity` 是更新后的绝对数量,且不得小于 `locked_quantity`。 SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。 @@ -157,7 +157,7 @@ SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。 { "sku_no": "SKU-RED-M", "price": 9900, - "available_quantity": 20, + "stock_quantity": 20, "status": 1, "k1": "颜色", "v1": "红色", @@ -194,7 +194,7 @@ SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。 "sku_id": "726390485721088201", "sku_no": "SKU-RED-M", "price": 9900, - "available_quantity": 20, + "stock_quantity": 20, "status": 1, "is_archived": false, "version": 1 @@ -226,7 +226,7 @@ Content-Type: application/json 运营人员可以提交 `INVENTORY`、`ON_SALE`、`OFF_SALE`。无论商品是运营人员手动下架,还是因无可售库存自动切换为 `OFF_SALE`,都只能通过本接口显式重新设置为 `ON_SALE`;库存补充本身不会改变商品状态。 -上架时必须存在至少一个启用、未归档且 `available_quantity > locked_quantity` 的 SKU。 +上架时必须存在至少一个启用、未归档且 `stock_quantity > locked_quantity` 的 SKU。 ```json { diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index e7c023d..a2afd3b 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -27,7 +27,7 @@ var ErrInvalidLeafCategory = errors.New("category must be an existing second-lev // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") -// ErrInsufficientStock is returned when available - locked is less than the requested quantity. +// ErrInsufficientStock is returned when stock - locked is less than the requested quantity. var ErrInsufficientStock = errors.New("insufficient stock") // ErrProductNotOnSale is returned when a new inventory reservation targets a product that is not on sale. @@ -89,42 +89,42 @@ type ProductCountRecord struct { // SKURecord is the persistence model for product.product_items. type SKURecord struct { - ID string - ProductID string - SKUNo string - Name string - Price int64 - ImageIDs []string - AvailableQuantity int32 - LockedQuantity int32 - SoldQuantity int32 - AttributesJSON string - K1 string - V1 string - K2 string - V2 string - K3 string - V3 string - Status int32 - IsArchived bool - ArchivedAt *time.Time - Version int32 - DeletedAt *time.Time - CreatedAt time.Time - UpdatedAt time.Time - Inventory *InventoryRecord + ID string + ProductID string + SKUNo string + Name string + Price int64 + ImageIDs []string + StockQuantity int32 + LockedQuantity int32 + SoldQuantity int32 + AttributesJSON string + K1 string + V1 string + K2 string + V2 string + K3 string + V3 string + Status int32 + IsArchived bool + ArchivedAt *time.Time + Version int32 + DeletedAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time + Inventory *InventoryRecord } // InventoryRecord is the persistence model for product.product_item_inventory. type InventoryRecord struct { - ID string - SKUID string - AvailableQuantity int32 - LockedQuantity int32 - SoldQuantity int32 - Version int32 - CreatedAt time.Time - UpdatedAt time.Time + ID string + SKUID string + StockQuantity int32 + LockedQuantity int32 + SoldQuantity int32 + Version int32 + CreatedAt time.Time + UpdatedAt time.Time } // CartItemProductLookup identifies the SPU/SKU pair stored by one cart line. @@ -158,7 +158,7 @@ type SKUUpdate struct { ExpectedInventoryVersion int32 Name *string Price *int64 - AvailableQuantity *int32 + StockQuantity *int32 Status *int32 ImageIDs *[]string } @@ -209,17 +209,17 @@ type ProductStatusUpdate struct { // CategoryProductRecord is the product summary returned by product list endpoints. type CategoryProductRecord struct { - ID string - SPUNo string - Title string - Status productv1.ProductStatus - ImageIDs []string - Price int64 - SoldQuantity int64 - AvailableQuantity int64 - LockedQuantity int64 - CreatedAt time.Time - UpdatedAt time.Time + ID string + SPUNo string + Title string + Status productv1.ProductStatus + ImageIDs []string + Price int64 + SoldQuantity int64 + StockQuantity int64 + LockedQuantity int64 + CreatedAt time.Time + UpdatedAt time.Time } // CategoryRecord is the persistence model for product.product_category. @@ -340,7 +340,7 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, spu_no VARCHAR(100), sku_no VARCHAR(100), - available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), + stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0), locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), @@ -1267,9 +1267,9 @@ FOR UPDATE } } - if input.AvailableQuantity != nil { - if *input.AvailableQuantity < 0 { - return fmt.Errorf("available_quantity must be greater than or equal to 0") + if input.StockQuantity != nil { + if *input.StockQuantity < 0 { + return fmt.Errorf("stock_quantity must be greater than or equal to 0") } var lockedQuantity int32 var inventoryVersion int32 @@ -1288,14 +1288,14 @@ FOR UPDATE if inventoryVersion != input.ExpectedInventoryVersion { return ErrSKUVersionConflict } - if *input.AvailableQuantity < lockedQuantity { - return fmt.Errorf("available_quantity cannot be less than locked_quantity") + if *input.StockQuantity < lockedQuantity { + return fmt.Errorf("stock_quantity cannot be less than locked_quantity") } if _, err := tx.ExecContext(ctx, ` UPDATE product.product_item_inventory -SET available_quantity = $2, version = version + 1, updated_at = NOW() +SET stock_quantity = $2, version = version + 1, updated_at = NOW() WHERE sku_id = $1 AND version = $3 -`, skuID, *input.AvailableQuantity, input.ExpectedInventoryVersion); err != nil { +`, skuID, *input.StockQuantity, input.ExpectedInventoryVersion); err != nil { return fmt.Errorf("update sku inventory %s: %w", input.ID, err) } } @@ -1338,7 +1338,7 @@ SELECT EXISTS( AND pi.deleted_at IS NULL AND pi.is_archived = FALSE AND pi.status = 1 - AND inv.available_quantity > inv.locked_quantity + AND inv.stock_quantity > inv.locked_quantity ) `, productID).Scan(&exists) if err != nil { @@ -1363,7 +1363,7 @@ WHERE p.id = $1 AND pi.deleted_at IS NULL AND pi.is_archived = FALSE AND pi.status = 1 - AND inv.available_quantity > inv.locked_quantity + AND inv.stock_quantity > inv.locked_quantity ) `, productID, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE)) if err != nil { @@ -1440,7 +1440,7 @@ RETURNING id return fmt.Errorf("insert sku: %w", err) } - if _, err := insertSKUInventory(ctx, tx, inventoryID, skuID, sku.AvailableQuantity); err != nil { + if _, err := insertSKUInventory(ctx, tx, inventoryID, skuID, sku.StockQuantity); err != nil { return err } @@ -1484,7 +1484,7 @@ WHERE id = $1 AND is_archived = FALSE return ErrSKUNotFound } - if _, err := updateSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { + if _, err := updateSKUInventory(ctx, tx, id, sku.StockQuantity); err != nil { return err } @@ -1494,7 +1494,7 @@ WHERE id = $1 AND is_archived = FALSE return nil } -// LockInventory atomically reserves quantity when available_quantity - locked_quantity >= quantity. +// LockInventory atomically reserves quantity when stock_quantity - locked_quantity >= quantity. func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32) (*InventoryRecord, error) { if quantity <= 0 { return nil, fmt.Errorf("quantity must be positive") @@ -1546,8 +1546,8 @@ WHERE sku_id = $1 AND pi.is_archived = FALSE AND pi.status = 1 ) - AND available_quantity - locked_quantity >= $2 -RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at + AND stock_quantity - locked_quantity >= $2 +RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at `, id, quantity) inventory, err := scanInventory(row) if errors.Is(err, sql.ErrNoRows) { @@ -1781,13 +1781,13 @@ SELECT p.updated_at, COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), - COALESCE(sku_summary.available_quantity, 0), + COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.locked_quantity, 0) FROM product.products p LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, - SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, + SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity, SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id @@ -1860,13 +1860,13 @@ SELECT p.updated_at, COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), - COALESCE(sku_summary.available_quantity, 0), + COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.locked_quantity, 0) FROM product.products p LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, - SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, + SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity, SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id @@ -1969,14 +1969,14 @@ SELECT p.updated_at, COALESCE(to_json(p.image_ids)::text, '[]'), COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), - COALESCE(sku_summary.available_quantity, 0), + COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.locked_quantity, 0) FROM product.products p JOIN product.product_category_bindings b ON b.product_id = p.id LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, - SUM(COALESCE(inv.available_quantity, 0)) AS available_quantity, + SUM(COALESCE(inv.stock_quantity, 0)) AS stock_quantity, SUM(COALESCE(inv.locked_quantity, 0)) AS locked_quantity FROM product.product_items pi LEFT JOIN product.product_item_inventory inv ON inv.sku_id = pi.id @@ -2295,13 +2295,13 @@ RETURNING id, if err != nil { return nil, err } - inventory, err := insertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.AvailableQuantity) + inventory, err := insertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.StockQuantity) if err != nil { return nil, err } createdSKU.Inventory = inventory if inventory != nil { - createdSKU.AvailableQuantity = inventory.AvailableQuantity + createdSKU.StockQuantity = inventory.StockQuantity createdSKU.LockedQuantity = inventory.LockedQuantity createdSKU.SoldQuantity = inventory.SoldQuantity } @@ -2315,15 +2315,15 @@ func inventoryIDFromSKU(sku SKURecord) (int64, error) { return parseID(sku.Inventory.ID, "inventory id") } -func insertSKUInventory(ctx context.Context, tx *sql.Tx, inventoryID, skuID int64, availableQuantity int32) (*InventoryRecord, error) { +func insertSKUInventory(ctx context.Context, tx *sql.Tx, inventoryID, skuID int64, stockQuantity int32) (*InventoryRecord, error) { 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, stock_quantity) 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 = $2 -RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at -`, inventoryID, skuID, availableQuantity) +RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at +`, inventoryID, skuID, stockQuantity) inventory, err := scanInventory(row) if err != nil { return nil, fmt.Errorf("insert sku inventory %s: %w", formatID(skuID), err) @@ -2331,15 +2331,15 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, versio return inventory, nil } -func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, availableQuantity int32) (*InventoryRecord, error) { +func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, stockQuantity int32) (*InventoryRecord, error) { row := tx.QueryRowContext(ctx, ` UPDATE product.product_item_inventory -SET available_quantity = $2, +SET stock_quantity = $2, version = version + 1, updated_at = NOW() WHERE sku_id = $1 -RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, version, created_at, updated_at -`, skuID, availableQuantity) +RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at +`, skuID, stockQuantity) inventory, err := scanInventory(row) if errors.Is(err, sql.ErrNoRows) { return nil, fmt.Errorf("update sku inventory %s: %w", formatID(skuID), ErrSKUNotFound) @@ -2454,7 +2454,7 @@ SELECT pi.id, pi.updated_at, inv.id, inv.sku_id, - inv.available_quantity, + inv.stock_quantity, inv.locked_quantity, inv.sold_quantity, inv.version, @@ -2523,7 +2523,7 @@ SELECT pi.id, pi.updated_at, inv.id, inv.sku_id, - inv.available_quantity, + inv.stock_quantity, inv.locked_quantity, inv.sold_quantity, inv.version, @@ -2577,7 +2577,7 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { &imageIDsJSON, &rec.Price, &rec.SoldQuantity, - &rec.AvailableQuantity, + &rec.StockQuantity, &rec.LockedQuantity, ); err != nil { return nil, fmt.Errorf("scan category product: %w", err) @@ -2696,7 +2696,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { deletedAt sql.NullTime inventoryID sql.NullInt64 inventorySKUID sql.NullInt64 - availableQuantity sql.NullInt32 + stockQuantity sql.NullInt32 lockedQuantity sql.NullInt32 soldQuantity sql.NullInt32 inventoryVersion sql.NullInt32 @@ -2720,7 +2720,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { &rec.UpdatedAt, &inventoryID, &inventorySKUID, - &availableQuantity, + &stockQuantity, &lockedQuantity, &soldQuantity, &inventoryVersion, @@ -2758,12 +2758,12 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { } if inventoryID.Valid { rec.Inventory = &InventoryRecord{ - ID: formatID(inventoryID.Int64), - SKUID: formatID(inventorySKUID.Int64), - AvailableQuantity: nullInt32Value(availableQuantity), - LockedQuantity: nullInt32Value(lockedQuantity), - SoldQuantity: nullInt32Value(soldQuantity), - Version: nullInt32Value(inventoryVersion), + ID: formatID(inventoryID.Int64), + SKUID: formatID(inventorySKUID.Int64), + StockQuantity: nullInt32Value(stockQuantity), + LockedQuantity: nullInt32Value(lockedQuantity), + SoldQuantity: nullInt32Value(soldQuantity), + Version: nullInt32Value(inventoryVersion), } if inventoryCreatedAt.Valid { rec.Inventory.CreatedAt = inventoryCreatedAt.Time @@ -2771,7 +2771,7 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { if inventoryUpdatedAt.Valid { rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time } - rec.AvailableQuantity = rec.Inventory.AvailableQuantity + rec.StockQuantity = rec.Inventory.StockQuantity rec.LockedQuantity = rec.Inventory.LockedQuantity rec.SoldQuantity = rec.Inventory.SoldQuantity } @@ -2787,7 +2787,7 @@ func scanInventory(scanner rowScanner) (*InventoryRecord, error) { if err := scanner.Scan( &id, &skuID, - &rec.AvailableQuantity, + &rec.StockQuantity, &rec.LockedQuantity, &rec.SoldQuantity, &rec.Version, diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 9215a0e..0d0a696 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -1411,9 +1411,9 @@ func skuUpdateFromProto(input *productv1.PatchExistingSKU) (repository.SKUUpdate case "price": value := input.GetPrice() update.Price = &value - case "available_quantity": - value := input.GetAvailableQuantity() - update.AvailableQuantity = &value + case "stock_quantity": + value := input.GetStockQuantity() + update.StockQuantity = &value case "status": value := input.GetStatus() update.Status = &value @@ -1448,7 +1448,7 @@ func toProtoSKUChangeResult(result *repository.SKUChangeResult) *productv1.SKUCh func hasSellableSKURecord(skus []repository.SKURecord) bool { for _, sku := range skus { - if sku.Status == 1 && sku.AvailableQuantity > 0 { + if sku.Status == 1 && sku.StockQuantity > sku.LockedQuantity { return true } } @@ -1463,8 +1463,8 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, if sku.GetPrice() < 0 { return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") } - if sku.GetAvailableQuantity() < 0 { - return repository.SKURecord{}, errors.New("available_quantity must be greater than or equal to 0") + if sku.GetStockQuantity() < 0 { + return repository.SKURecord{}, errors.New("stock_quantity must be greater than or equal to 0") } attrs, derivedName, err := buildSKUAttributesAndName(sku) @@ -1481,19 +1481,19 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, } return repository.SKURecord{ - 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, + SKUNo: strings.TrimSpace(sku.GetSkuNo()), + Name: name, + Price: sku.GetPrice(), + ImageIDs: normalizeStringList(sku.GetImageIds()), + StockQuantity: sku.GetStockQuantity(), + 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 } @@ -1691,29 +1691,29 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco protoSKUs := make([]*productv1.SKU, 0, len(skus)) for _, sku := range skus { 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, - IsArchived: sku.IsArchived, - ArchivedAt: timePtrToMillisString(sku.ArchivedAt), - Version: sku.Version, - DeletedAt: timePtrToMillisString(sku.DeletedAt), - CreatedAt: timeToMillisString(sku.CreatedAt), - UpdatedAt: timeToMillisString(sku.UpdatedAt), - Inventory: toProtoInventory(sku.Inventory), + SkuId: sku.ID, + ProductId: sku.ProductID, + SkuNo: sku.SKUNo, + Name: sku.Name, + Price: sku.Price, + StockQuantity: sku.StockQuantity, + 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, + IsArchived: sku.IsArchived, + ArchivedAt: timePtrToMillisString(sku.ArchivedAt), + Version: sku.Version, + DeletedAt: timePtrToMillisString(sku.DeletedAt), + CreatedAt: timeToMillisString(sku.CreatedAt), + UpdatedAt: timeToMillisString(sku.UpdatedAt), + Inventory: toProtoInventory(sku.Inventory), }) } @@ -1768,7 +1768,7 @@ func toProtoCartItemProduct(lineID string, record repository.CartItemProductReco result.SkuName = record.SKU.Name result.Price = record.SKU.Price result.SkuImageIds = record.SKU.ImageIDs - result.SkuAvailableQuantity = record.SKU.AvailableQuantity + result.SkuStockQuantity = record.SKU.StockQuantity result.SkuLockedQuantity = record.SKU.LockedQuantity result.SkuStatus = record.SKU.Status result.SkuIsArchived = record.SKU.IsArchived @@ -1780,17 +1780,17 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv return nil } return &productv1.CategoryProduct{ - UpdatedAt: timeToMillisString(product.UpdatedAt), - CreatedAt: timeToMillisString(product.CreatedAt), - Title: product.Title, - ProductId: product.ID, - SpuNo: product.SPUNo, - Status: product.Status, - ImageIds: product.ImageIDs, - Price: product.Price, - SoldQuantity: product.SoldQuantity, - AvailableQuantity: product.AvailableQuantity, - LockedQuantity: product.LockedQuantity, + UpdatedAt: timeToMillisString(product.UpdatedAt), + CreatedAt: timeToMillisString(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Price: product.Price, + SoldQuantity: product.SoldQuantity, + StockQuantity: product.StockQuantity, + LockedQuantity: product.LockedQuantity, } } @@ -1799,14 +1799,14 @@ func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductI return nil } return &productv1.ProductItemInventory{ - InventoryId: inventory.ID, - SkuId: inventory.SKUID, - AvailableQuantity: inventory.AvailableQuantity, - LockedQuantity: inventory.LockedQuantity, - SoldQuantity: inventory.SoldQuantity, - Version: inventory.Version, - CreatedAt: timeToMillisString(inventory.CreatedAt), - UpdatedAt: timeToMillisString(inventory.UpdatedAt), + InventoryId: inventory.ID, + SkuId: inventory.SKUID, + StockQuantity: inventory.StockQuantity, + LockedQuantity: inventory.LockedQuantity, + SoldQuantity: inventory.SoldQuantity, + Version: inventory.Version, + CreatedAt: timeToMillisString(inventory.CreatedAt), + UpdatedAt: timeToMillisString(inventory.UpdatedAt), } } diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 4079689..0a339ff 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -207,7 +207,7 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, spu_no VARCHAR(100), sku_no VARCHAR(100), - available_quantity INTEGER NOT NULL DEFAULT 0 CHECK (available_quantity >= 0), + stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0), locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0), sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0), version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0), @@ -216,11 +216,11 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); -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.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账'; -COMMENT ON COLUMN product.product_item_inventory.available_quantity IS 'SKU 当前可售库存'; +COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前库存池数量,净可售=stock_quantity-locked_quantity'; COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存'; COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量'; COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版本号'; diff --git a/scripts/sql/rename-inventory-stock-quantity.sql b/scripts/sql/rename-inventory-stock-quantity.sql new file mode 100644 index 0000000..bfb6007 --- /dev/null +++ b/scripts/sql/rename-inventory-stock-quantity.sql @@ -0,0 +1,5 @@ +ALTER TABLE product.product_item_inventory + RENAME COLUMN available_quantity TO stock_quantity; + +COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储库存池、锁定库存和已售数量'; +COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前库存池数量,净可售=stock_quantity-locked_quantity'; From cf068fe61011c43d913b5bf8fcce301da3d36c6d Mon Sep 17 00:00:00 2001 From: robinj0726 <88188467+robinj0726@users.noreply.github.com> Date: Sat, 5 Sep 2026 15:22:16 +0800 Subject: [PATCH 44/44] feat(product): implement inventory adjustment functionality with confirm and release actions --- internal/repository/product_repository.go | 226 +++++++++++++++++- .../repository/product_repository_test.go | 29 +++ internal/server/product_server.go | 95 ++++++++ scripts/sql/create-inventory-adjustments.sql | 14 ++ scripts/sql/recreate-product-tables.sql | 13 + 5 files changed, 376 insertions(+), 1 deletion(-) create mode 100644 scripts/sql/create-inventory-adjustments.sql diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index a2afd3b..9051dd6 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "sort" "strconv" "strings" "time" @@ -30,6 +31,12 @@ var ErrSKUNotFound = errors.New("sku not found") // ErrInsufficientStock is returned when stock - locked is less than the requested quantity. var ErrInsufficientStock = errors.New("insufficient stock") +// ErrInsufficientLockedStock is returned when locked stock is less than the requested quantity. +var ErrInsufficientLockedStock = errors.New("insufficient locked stock") + +// ErrInventoryAdjustmentConflict is returned when an idempotent inventory adjustment is replayed with different data. +var ErrInventoryAdjustmentConflict = errors.New("inventory adjustment conflict") + // ErrProductNotOnSale is returned when a new inventory reservation targets a product that is not on sale. var ErrProductNotOnSale = errors.New("product is not on sale") @@ -127,6 +134,12 @@ type InventoryRecord struct { UpdatedAt time.Time } +// InventoryAdjustment is one order item quantity to confirm or release. +type InventoryAdjustment struct { + SKUID string + Quantity int32 +} + // CartItemProductLookup identifies the SPU/SKU pair stored by one cart line. // Line IDs are intentionally kept outside the repository because they belong to trade.cart_items. type CartItemProductLookup struct { @@ -348,6 +361,15 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); +CREATE TABLE IF NOT EXISTS product.inventory_adjustments ( + order_id BIGINT NOT NULL, + action VARCHAR(20) NOT NULL, + sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, + quantity INTEGER NOT NULL CHECK (quantity > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (order_id, action, sku_id), + CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release')) +); ALTER TABLE product.product_items ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_items @@ -1572,9 +1594,211 @@ RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, c return inventory, nil } +// ConfirmInventory converts locked stock to sold stock after payment succeeds. +func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment) ([]*InventoryRecord, error) { + return r.applyInventoryAdjustments(ctx, orderID, "confirm", items) +} + +// ReleaseInventory releases locked stock when a pending order is cancelled or expires. +func (r *ProductRepository) ReleaseInventory(ctx context.Context, orderID string, items []InventoryAdjustment) ([]*InventoryRecord, error) { + return r.applyInventoryAdjustments(ctx, orderID, "release", items) +} + +func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, orderID, action string, items []InventoryAdjustment) ([]*InventoryRecord, error) { + parsedOrderID, err := parseID(orderID, "order id") + if err != nil { + return nil, err + } + aggregated, err := aggregateInventoryAdjustments(items) + if err != nil { + return nil, err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin %s inventory: %w", action, err) + } + defer tx.Rollback() + + inventories := make([]*InventoryRecord, 0, len(aggregated)) + for _, item := range aggregated { + skuID, err := parseID(item.SKUID, "sku id") + if err != nil { + return nil, err + } + + var inserted bool + err = tx.QueryRowContext(ctx, ` +INSERT INTO product.inventory_adjustments (order_id, action, sku_id, quantity) +VALUES ($1, $2, $3, $4) +ON CONFLICT (order_id, action, sku_id) DO NOTHING +RETURNING TRUE +`, parsedOrderID, action, skuID, item.Quantity).Scan(&inserted) + if errors.Is(err, sql.ErrNoRows) { + recordedQuantity, err := loadInventoryAdjustmentQuantity(ctx, tx, parsedOrderID, action, skuID) + if err != nil { + return nil, err + } + if recordedQuantity != item.Quantity { + return nil, fmt.Errorf("%s inventory %s: %w: recorded quantity %d, requested quantity %d", action, formatID(skuID), ErrInventoryAdjustmentConflict, recordedQuantity, item.Quantity) + } + inventory, err := loadInventoryForUpdate(ctx, tx, skuID) + if err != nil { + return nil, err + } + inventories = append(inventories, inventory) + continue + } + if err != nil { + return nil, fmt.Errorf("record %s inventory adjustment: %w", action, err) + } + + inventory, err := applyInventoryAdjustment(ctx, tx, action, skuID, item.Quantity) + if err != nil { + return nil, err + } + inventories = append(inventories, inventory) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit %s inventory: %w", action, err) + } + return inventories, nil +} + +func aggregateInventoryAdjustments(items []InventoryAdjustment) ([]InventoryAdjustment, error) { + if len(items) == 0 { + return nil, errors.New("items are required") + } + type aggregate struct { + skuID string + parsedID int64 + quantity int32 + } + quantities := make(map[string]int32, len(items)) + parsedIDs := make(map[string]int64, len(items)) + for i, item := range items { + if strings.TrimSpace(item.SKUID) == "" { + return nil, fmt.Errorf("items[%d].sku_id is required", i) + } + if item.Quantity <= 0 { + return nil, fmt.Errorf("items[%d].quantity must be positive", i) + } + skuID := strings.TrimSpace(item.SKUID) + parsedID, err := parseID(skuID, fmt.Sprintf("items[%d].sku_id", i)) + if err != nil { + return nil, err + } + quantities[skuID] += item.Quantity + parsedIDs[skuID] = parsedID + } + aggregated := make([]aggregate, 0, len(quantities)) + for skuID, quantity := range quantities { + aggregated = append(aggregated, aggregate{skuID: skuID, parsedID: parsedIDs[skuID], quantity: quantity}) + } + sort.Slice(aggregated, func(i, j int) bool { + return aggregated[i].parsedID < aggregated[j].parsedID + }) + out := make([]InventoryAdjustment, 0, len(aggregated)) + for _, item := range aggregated { + out = append(out, InventoryAdjustment{SKUID: item.skuID, Quantity: item.quantity}) + } + return out, nil +} + +func applyInventoryAdjustment(ctx context.Context, tx *sql.Tx, action string, skuID int64, quantity int32) (*InventoryRecord, error) { + var query string + switch action { + case "confirm": + query = ` +UPDATE product.product_item_inventory +SET stock_quantity = stock_quantity - $2, + locked_quantity = locked_quantity - $2, + sold_quantity = sold_quantity + $2, + version = version + 1, + updated_at = NOW() +WHERE sku_id = $1 + AND locked_quantity >= $2 + AND stock_quantity >= $2 +RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at +` + case "release": + query = ` +UPDATE product.product_item_inventory +SET locked_quantity = locked_quantity - $2, + version = version + 1, + updated_at = NOW() +WHERE sku_id = $1 + AND locked_quantity >= $2 +RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at +` + default: + return nil, fmt.Errorf("unsupported inventory action %q", action) + } + + inventory, err := scanInventory(tx.QueryRowContext(ctx, query, skuID, quantity)) + if errors.Is(err, sql.ErrNoRows) { + exists, existsErr := skuInventoryExistsInTx(ctx, tx, skuID) + if existsErr != nil { + return nil, existsErr + } + if !exists { + return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrSKUNotFound) + } + return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrInsufficientLockedStock) + } + if err != nil { + return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), err) + } + return inventory, nil +} + +func loadInventoryForUpdate(ctx context.Context, tx *sql.Tx, skuID int64) (*InventoryRecord, error) { + inventory, err := scanInventory(tx.QueryRowContext(ctx, ` +SELECT id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, created_at, updated_at +FROM product.product_item_inventory +WHERE sku_id = $1 +FOR UPDATE +`, skuID)) + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("load inventory %s: %w", formatID(skuID), ErrSKUNotFound) + } + if err != nil { + return nil, fmt.Errorf("load inventory %s: %w", formatID(skuID), err) + } + return inventory, nil +} + +func loadInventoryAdjustmentQuantity(ctx context.Context, tx *sql.Tx, orderID int64, action string, skuID int64) (int32, error) { + var quantity int32 + err := tx.QueryRowContext(ctx, ` +SELECT quantity +FROM product.inventory_adjustments +WHERE order_id = $1 + AND action = $2 + AND sku_id = $3 +FOR UPDATE +`, orderID, action, skuID).Scan(&quantity) + if errors.Is(err, sql.ErrNoRows) { + return 0, fmt.Errorf("%s inventory %s: %w: missing recorded adjustment", action, formatID(skuID), ErrInventoryAdjustmentConflict) + } + if err != nil { + return 0, fmt.Errorf("load %s inventory adjustment %s: %w", action, formatID(skuID), err) + } + return quantity, nil +} + func (r *ProductRepository) skuInventoryExists(ctx context.Context, skuID int64) (bool, error) { + return skuInventoryExistsInTx(ctx, r.db, skuID) +} + +type queryRower interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func skuInventoryExistsInTx(ctx context.Context, q queryRower, skuID int64) (bool, error) { var exists bool - err := r.db.QueryRowContext(ctx, ` + err := q.QueryRowContext(ctx, ` SELECT EXISTS( SELECT 1 FROM product.product_item_inventory inv diff --git a/internal/repository/product_repository_test.go b/internal/repository/product_repository_test.go index 7ebc161..45de7b4 100644 --- a/internal/repository/product_repository_test.go +++ b/internal/repository/product_repository_test.go @@ -8,3 +8,32 @@ func TestEscapeLikeLiteral(t *testing.T) { t.Fatalf("escapeLikeLiteral(%q) = %q, want %q", input, got, want) } } + +func TestAggregateInventoryAdjustments(t *testing.T) { + got, err := aggregateInventoryAdjustments([]InventoryAdjustment{ + {SKUID: "1002", Quantity: 3}, + {SKUID: "1001", Quantity: 1}, + {SKUID: "1001", Quantity: 2}, + }) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 { + t.Fatalf("len = %d, want 2", len(got)) + } + if got[0] != (InventoryAdjustment{SKUID: "1001", Quantity: 3}) { + t.Fatalf("first adjustment = %#v", got[0]) + } + if got[1] != (InventoryAdjustment{SKUID: "1002", Quantity: 3}) { + t.Fatalf("second adjustment = %#v", got[1]) + } +} + +func TestAggregateInventoryAdjustmentsRejectsInvalidSKUID(t *testing.T) { + _, err := aggregateInventoryAdjustments([]InventoryAdjustment{ + {SKUID: "bad-sku", Quantity: 1}, + }) + if err == nil { + t.Fatal("expected invalid sku id error") + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 0d0a696..3f274ef 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -881,6 +881,93 @@ func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockIn }, nil } +// ConfirmInventory converts locked stock into sold stock for a paid order. +func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.ConfirmInventoryRequest) (*productv1.ConfirmInventoryResponse, error) { + if req == nil || req.GetOrderId() == "" { + return nil, status.Error(codes.InvalidArgument, "order_id is required") + } + items, err := toRepositoryInventoryAdjustments(req.GetItems()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.confirm_inventory", trace.WithAttributes( + attribute.String("order.id", req.GetOrderId()), + attribute.Int("inventory.items", len(items)), + )) + defer dbSpan.End() + + inventories, err := s.repo.ConfirmInventory(dbCtx, req.GetOrderId(), items) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + return nil, mapInventoryAdjustmentError(ctx, s, "confirm", err) + } + return &productv1.ConfirmInventoryResponse{Inventories: toProtoInventories(inventories)}, nil +} + +// ReleaseInventory releases locked stock for an unpaid closed order. +func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.ReleaseInventoryRequest) (*productv1.ReleaseInventoryResponse, error) { + if req == nil || req.GetOrderId() == "" { + return nil, status.Error(codes.InvalidArgument, "order_id is required") + } + items, err := toRepositoryInventoryAdjustments(req.GetItems()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.release_inventory", trace.WithAttributes( + attribute.String("order.id", req.GetOrderId()), + attribute.Int("inventory.items", len(items)), + )) + defer dbSpan.End() + + inventories, err := s.repo.ReleaseInventory(dbCtx, req.GetOrderId(), items) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + return nil, mapInventoryAdjustmentError(ctx, s, "release", err) + } + return &productv1.ReleaseInventoryResponse{Inventories: toProtoInventories(inventories)}, nil +} + +func toRepositoryInventoryAdjustments(items []*productv1.InventoryAdjustmentItem) ([]repository.InventoryAdjustment, error) { + if len(items) == 0 { + return nil, errors.New("items are required") + } + out := make([]repository.InventoryAdjustment, 0, len(items)) + for i, item := range items { + if item == nil { + return nil, fmt.Errorf("items[%d] is required", i) + } + if item.GetSkuId() == "" { + return nil, fmt.Errorf("items[%d].sku_id is required", i) + } + if item.GetQuantity() <= 0 { + return nil, fmt.Errorf("items[%d].quantity must be positive", i) + } + out = append(out, repository.InventoryAdjustment{ + SKUID: item.GetSkuId(), + Quantity: item.GetQuantity(), + }) + } + return out, nil +} + +func mapInventoryAdjustmentError(ctx context.Context, s *ProductServer, action string, err error) error { + switch { + case errors.Is(err, repository.ErrSKUNotFound): + return status.Error(codes.NotFound, "sku inventory not found") + case errors.Is(err, repository.ErrInsufficientLockedStock): + return status.Error(codes.FailedPrecondition, "insufficient locked stock") + case errors.Is(err, repository.ErrInventoryAdjustmentConflict): + return status.Error(codes.FailedPrecondition, "inventory adjustment conflict") + default: + s.observer.Logger(ctx).Error(action+" inventory failed", zap.Error(err)) + return status.Errorf(codes.Internal, "%s inventory: %v", action, err) + } +} + func totalPages(total int64, pageSize int32) int32 { if total <= 0 || pageSize <= 0 { return 0 @@ -1810,6 +1897,14 @@ func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductI } } +func toProtoInventories(inventories []*repository.InventoryRecord) []*productv1.ProductItemInventory { + out := make([]*productv1.ProductItemInventory, 0, len(inventories)) + for _, inventory := range inventories { + out = append(out, toProtoInventory(inventory)) + } + return out +} + func buildCategoryTree(categories []*repository.CategoryRecord) []*productv1.CategoryNode { nodes := make(map[string]*productv1.CategoryNode, len(categories)) records := make(map[string]*repository.CategoryRecord, len(categories)) diff --git a/scripts/sql/create-inventory-adjustments.sql b/scripts/sql/create-inventory-adjustments.sql new file mode 100644 index 0000000..3dc2ba0 --- /dev/null +++ b/scripts/sql/create-inventory-adjustments.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS product.inventory_adjustments ( + order_id BIGINT NOT NULL, + action VARCHAR(20) NOT NULL, + sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, + quantity INTEGER NOT NULL CHECK (quantity > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (order_id, action, sku_id), + CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release')) +); + +COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存'; +COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定'; + +GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product; diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 0a339ff..c83d36f 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -216,6 +216,16 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); +CREATE TABLE IF NOT EXISTS product.inventory_adjustments ( + order_id BIGINT NOT NULL, + action VARCHAR(20) NOT NULL, + sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE, + quantity INTEGER NOT NULL CHECK (quantity > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (order_id, action, sku_id), + CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release')) +); + 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 编码冗余字段,用于库存查询和对账'; @@ -224,6 +234,8 @@ COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前 COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存'; COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量'; COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版本号'; +COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存'; +COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定'; DROP TRIGGER IF EXISTS set_products_updated_at ON product.products; CREATE TRIGGER set_products_updated_at @@ -245,3 +257,4 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category_bindings TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product;