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, ", "))