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,