feat: allow non-unique SKU business codes and optional SPU codes; update related database constraints

This commit is contained in:
BXY 2026-10-10 13:01:19 +08:00
parent d4ef3b5a57
commit c2d0aa604f
9 changed files with 87 additions and 75 deletions

View File

@ -40,7 +40,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。
当前创建接口不再接收 `product_id`、`sku_id`、`inventory_id` 和 SKU `name`:`product_id`、`sku_id`、`inventory_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 当前创建接口不接收 `product_id`、`sku_id`、`inventory_id`:这些 ID 均由商品服务应用层生成雪花 ID。SKU `name` 可显式传入;未传时由后端按规格值 `v1/v2/v3` 拼接。
创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成: 创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成:
@ -56,7 +56,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| 字段 | 必填 | 说明 | | 字段 | 必填 | 说明 |
|---|---:|---| |---|---:|---|
| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 | | `spu_no` | 否 | 商品业务编码;空值可重复,非空值在当前店铺未删除商品中唯一 |
| `title` | 是 | 商品标题 | | `title` | 是 | 商品标题 |
| `selling_point` | 否 | 商品卖点 | | `selling_point` | 否 | 商品卖点 |
| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 | | `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 |
@ -69,7 +69,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
| `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` | | `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` |
| `skus` | 否 | SKU 列表 | | `skus` | 否 | SKU 列表 |
`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。 `skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。`sku_no` 和 `name` 均可为空或重复,SKU 主键才是唯一标识。
最小示例: 最小示例:

View File

@ -266,17 +266,7 @@ SKU 协议需要增加 `is_archived`、`archived_at` 与版本字段。普通接
迁移后,`status` 默认值为 `1`,约束为 `status IN (1, 2, 3)`。 迁移后,`status` 默认值为 `1`,约束为 `status IN (1, 2, 3)`。
SKU 编号唯一索引只约束当前有效 SKU: SKU 编号不建立唯一索引。`sku_no` 和 SKU 名称均为业务展示字段,可在同一店铺的当前 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. 实施位置 ## 6. 实施位置

View File

@ -73,9 +73,6 @@ var ErrSKUReplacementRequiresNotOnSale = errors.New("sku replacement requires in
// ErrSameStore is returned when a store transfer targets the product's current store. // ErrSameStore is returned when a store transfer targets the product's current store.
var ErrSameStore = errors.New("target store is the current store") var ErrSameStore = errors.New("target store is the current store")
// ErrDuplicateSKUNo is returned when the destination store already has an active SKU number.
var ErrDuplicateSKUNo = errors.New("sku_no already exists in target store")
// ProductRecord is the persistence model for product.products (SPU). // ProductRecord is the persistence model for product.products (SPU).
type ProductRecord struct { type ProductRecord struct {
ID string ID string
@ -536,7 +533,10 @@ ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS store_id BIGINT;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS weight_kg DOUBLE PRECISION; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS weight_kg DOUBLE PRECISION;
ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS barcode VARCHAR(64); ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS barcode VARCHAR(64);
DROP INDEX IF EXISTS product.uq_products_spu_no; DROP INDEX IF EXISTS product.uq_products_spu_no;
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no ON product.products (store_id, spu_no) WHERE deleted_at IS NULL; DROP INDEX IF EXISTS product.uq_products_store_spu_no;
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no
ON product.products (store_id, spu_no)
WHERE deleted_at IS NULL AND spu_no <> '';
CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id); CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id);
CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id
@ -556,9 +556,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name
WHERE node_type = 1; WHERE node_type = 1;
DROP INDEX IF EXISTS product.uq_product_items_sku_no; DROP INDEX IF EXISTS product.uq_product_items_sku_no;
DROP INDEX IF EXISTS product.uq_product_items_sku_no_active; DROP INDEX IF EXISTS product.uq_product_items_sku_no_active;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_store_sku_no_active DROP INDEX IF EXISTS product.uq_product_items_store_sku_no_active;
ON product.product_items (store_id, sku_no)
WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
CREATE INDEX IF NOT EXISTS idx_product_items_store_id ON product.product_items (store_id) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_product_items_store_id ON product.product_items (store_id) WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS product.suppliers ( CREATE TABLE IF NOT EXISTS product.suppliers (
id BIGINT PRIMARY KEY, id BIGINT PRIMARY KEY,
@ -1900,6 +1898,7 @@ FOR UPDATE
return nil, fmt.Errorf("lock product %s: %w", productID, err) return nil, fmt.Errorf("lock product %s: %w", productID, err)
} }
if strings.TrimSpace(spuNo) != "" {
var taken int var taken int
if err := tx.QueryRowContext(ctx, ` if err := tx.QueryRowContext(ctx, `
SELECT 1 SELECT 1
@ -1912,30 +1911,6 @@ LIMIT 1
if taken == 1 { if taken == 1 {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo) return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo)
} }
var conflictSKU string
if err := tx.QueryRowContext(ctx, `
SELECT pi.sku_no
FROM product.product_items pi
WHERE pi.product_id = $1
AND pi.deleted_at IS NULL
AND pi.is_archived = FALSE
AND pi.sku_no IS NOT NULL
AND EXISTS (
SELECT 1
FROM product.product_items other
WHERE other.store_id = $2
AND other.sku_no = pi.sku_no
AND other.deleted_at IS NULL
AND other.is_archived = FALSE
AND other.product_id <> $1
)
LIMIT 1
`, id, targetStoreID).Scan(&conflictSKU); err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("check target sku_no: %w", err)
}
if conflictSKU != "" {
return nil, fmt.Errorf("%w: %s", ErrDuplicateSKUNo, conflictSKU)
} }
if _, err := tx.ExecContext(ctx, ` if _, err := tx.ExecContext(ctx, `
@ -1953,9 +1928,6 @@ UPDATE product.product_items
SET store_id = $2 SET store_id = $2
WHERE product_id = $1 AND store_id = $3 WHERE product_id = $1 AND store_id = $3
`, id, targetStoreID, scope.StoreID); err != nil { `, id, targetStoreID, scope.StoreID); err != nil {
if isPostgresConstraintError(err, "23505", "uq_product_items_store_sku_no_active") {
return nil, ErrDuplicateSKUNo
}
return nil, fmt.Errorf("update sku store: %w", err) return nil, fmt.Errorf("update sku store: %w", err)
} }
if _, err := tx.ExecContext(ctx, ` if _, err := tx.ExecContext(ctx, `

View File

@ -0,0 +1,42 @@
package server
import (
"testing"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
)
func TestProductFromCreateRequestAllowsEmptySPUNoAndRepeatedSKUFields(t *testing.T) {
request := &productv1.CreateProductRequest{
Title: "Product without business codes",
Skus: []*productv1.CreateProductSKU{
{
SkuNo: "SKU-REUSED",
Name: "Same SKU name",
Price: 100,
StockQuantity: 1,
K1: "Color",
V1: "Red",
},
{
SkuNo: "SKU-REUSED",
Name: "Same SKU name",
Price: 200,
StockQuantity: 2,
K1: "Color",
V1: "Blue",
},
},
}
product, skus, err := productFromCreateRequest(request)
if err != nil {
t.Fatalf("productFromCreateRequest() error = %v", err)
}
if product.SPUNo != "" {
t.Fatalf("SPUNo = %q, want empty", product.SPUNo)
}
if len(skus) != 2 || skus[0].SKUNo != skus[1].SKUNo || skus[0].Name != skus[1].Name {
t.Fatalf("repeated SKU fields were not preserved: %#v", skus)
}
}

View File

@ -531,7 +531,7 @@ func (s *ProductServer) TransferProductStore(ctx context.Context, req *productv1
return nil, status.Error(codes.NotFound, "product not found") return nil, status.Error(codes.NotFound, "product not found")
case errors.Is(err, repository.ErrSameStore): case errors.Is(err, repository.ErrSameStore):
return nil, status.Error(codes.InvalidArgument, "target store is the current store") return nil, status.Error(codes.InvalidArgument, "target store is the current store")
case errors.Is(err, repository.ErrDuplicateSPUNo), errors.Is(err, repository.ErrDuplicateSKUNo): case errors.Is(err, repository.ErrDuplicateSPUNo):
return nil, status.Error(codes.AlreadyExists, err.Error()) return nil, status.Error(codes.AlreadyExists, err.Error())
default: default:
s.observer.Logger(ctx).Error("transfer product store failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) s.observer.Logger(ctx).Error("transfer product store failed", zap.String("product_id", req.GetProductId()), zap.Error(err))
@ -617,7 +617,7 @@ func (s *ProductServer) CopyProductToStore(ctx context.Context, req *productv1.C
created, _, err := s.repo.CreateProductWithSKUs(ctx, target, targetSKUs) created, _, err := s.repo.CreateProductWithSKUs(ctx, target, targetSKUs)
if err != nil { if err != nil {
if errors.Is(err, repository.ErrDuplicateSPUNo) || errors.Is(err, repository.ErrDuplicateSKUNo) { if errors.Is(err, repository.ErrDuplicateSPUNo) {
return nil, status.Error(codes.AlreadyExists, err.Error()) return nil, status.Error(codes.AlreadyExists, err.Error())
} }
return nil, status.Errorf(codes.Internal, "copy product to target store: %v", err) return nil, status.Errorf(codes.Internal, "copy product to target store: %v", err)
@ -1951,9 +1951,6 @@ func normalizeNodeStatus(statusValue *int32) (int32, error) {
func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) { func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) {
spuNo := strings.TrimSpace(req.GetSpuNo()) spuNo := strings.TrimSpace(req.GetSpuNo())
if spuNo == "" {
return repository.ProductRecord{}, nil, errors.New("spu_no is required")
}
title := strings.TrimSpace(req.GetTitle()) title := strings.TrimSpace(req.GetTitle())
if title == "" { if title == "" {

View File

@ -85,7 +85,8 @@ CREATE INDEX IF NOT EXISTS idx_products_active_created_id
CREATE INDEX IF NOT EXISTS idx_products_store_active_created_id CREATE INDEX IF NOT EXISTS idx_products_store_active_created_id
ON product.products (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL; ON product.products (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no
ON product.products (store_id, spu_no) WHERE deleted_at IS NULL; ON product.products (store_id, spu_no)
WHERE deleted_at IS NULL AND spu_no <> '';
-- Storefront catalog classification and product group tables. -- Storefront catalog classification and product group tables.
CREATE TABLE IF NOT EXISTS product.catalog_category ( CREATE TABLE IF NOT EXISTS product.catalog_category (
@ -264,9 +265,7 @@ CREATE INDEX IF NOT EXISTS idx_product_items_price
ON product.product_items (price) WHERE deleted_at IS NULL AND is_archived = FALSE; ON product.product_items (price) WHERE deleted_at IS NULL AND is_archived = FALSE;
CREATE INDEX IF NOT EXISTS idx_product_items_store_id CREATE INDEX IF NOT EXISTS idx_product_items_store_id
ON product.product_items (store_id) WHERE deleted_at IS NULL; ON product.product_items (store_id) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_store_sku_no_active -- SKU business codes are display/import data and are intentionally not unique.
ON product.product_items (store_id, sku_no)
WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
CREATE TABLE IF NOT EXISTS product.product_item_inventory ( CREATE TABLE IF NOT EXISTS product.product_item_inventory (
id BIGINT PRIMARY KEY, id BIGINT PRIMARY KEY,

View File

@ -0,0 +1,17 @@
-- One-time migration for optional SPU codes and non-unique SKU business codes.
-- Run during a maintenance window before deploying the corresponding service code.
-- CREATE/DROP INDEX CONCURRENTLY must not be wrapped in a transaction.
-- Empty SPU codes are allowed multiple times in one store. Non-empty active
-- product codes remain unique within their store.
DROP INDEX CONCURRENTLY IF EXISTS product.uq_products_spu_no;
DROP INDEX CONCURRENTLY IF EXISTS product.uq_products_store_spu_no;
CREATE UNIQUE INDEX CONCURRENTLY uq_products_store_spu_no
ON product.products (store_id, spu_no)
WHERE deleted_at IS NULL AND spu_no <> '';
-- SKU business codes are not identifiers and may repeat, including among
-- active SKUs in the same store. SKU primary keys remain the stable identity.
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no_active;
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_store_sku_no_active;

View File

@ -38,17 +38,14 @@ ALTER TABLE product.products
COMMIT; COMMIT;
-- CREATE INDEX CONCURRENTLY cannot run inside the transaction above. -- SKU business codes are no longer unique. Remove the legacy uniqueness index
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_product_items_sku_no_active -- when this migration is applied to an existing deployment.
ON product.product_items (sku_no) DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no_active;
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 CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_items_active_product_id
ON product.product_items (product_id) ON product.product_items (product_id)
WHERE deleted_at IS NULL WHERE deleted_at IS NULL
AND is_archived = FALSE; AND is_archived = FALSE;
-- Drop the legacy index only after uq_product_items_sku_no_active is valid. -- Remove the older legacy index as well, if it is still present.
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no; DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;

View File

@ -110,7 +110,7 @@ CREATE INDEX IF NOT EXISTS idx_products_active_created_id
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no
ON product.products (spu_no) ON product.products (spu_no)
WHERE deleted_at IS NULL; WHERE deleted_at IS NULL AND spu_no <> '';
CREATE TABLE IF NOT EXISTS product.catalog_category ( CREATE TABLE IF NOT EXISTS product.catalog_category (
id BIGINT PRIMARY KEY, id BIGINT PRIMARY KEY,
@ -239,9 +239,7 @@ CREATE INDEX IF NOT EXISTS idx_product_items_price
ON product.product_items (price) ON product.product_items (price)
WHERE deleted_at IS NULL; WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active -- SKU business codes are not unique; use the SKU primary key for identity.
ON product.product_items (sku_no)
WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
CREATE TABLE IF NOT EXISTS product.product_item_inventory ( CREATE TABLE IF NOT EXISTS product.product_item_inventory (
id BIGINT PRIMARY KEY, id BIGINT PRIMARY KEY,