diff --git a/.env.example b/.env.example index aec6d8b..1d7d2e1 100644 --- a/.env.example +++ b/.env.example @@ -1,16 +1,18 @@ -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 +SNOWFLAKE_WORKER_ID=1 + # 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/.gitignore b/.gitignore index 7ed088c..3d87d50 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .env /bin/ *.exe +.DS_Store diff --git a/AGENTS.md b/AGENTS.md index fe10a16..09996bc 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,15 +45,14 @@ 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.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 a085d2b..1e2b911 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 @@ -8,18 +8,173 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格 | RPC | 说明 | 主要调用方 | |-----|------|-----------| -| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 / 订单服务 | -| `BatchGetProducts` | 批量拉取商品快照,减少算价阶段 N 次 RPC | `ids-svc-order` | +| `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 / 商城前台 | +| `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF | 契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。 +## 接口清单 + +商品服务对外接口的 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` | 分页查询全部未软删除商品 | +| `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 分页查询商品列表 | +| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 | + +### `CreateProduct` + +创建商品的完整字段、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` 拼接。 + +创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成: + +| ID | 生成方式 | 写入位置 | +|---|---|---| +| `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_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` | + +常用请求字段: + +| 字段 | 必填 | 说明 | +|---|---:|---| +| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 | +| `title` | 是 | 商品标题 | +| `selling_point` | 否 | 商品卖点 | +| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 | +| `image_ids` | 否 | 商品图片 ID 列表 | +| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID | +| `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 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。 + +最小示例: + +```json +{ + "spu_no": "SPU202607100001", + "title": "澳洲和牛家庭装", + "selling_point": "原切谷饲,冷链到家", + "leaf_category_ids": ["726390485721088000"], + "skus": [ + { + "sku_no": "SKU20260710000101", + "price": 12800, + "stock_quantity": 100, + "k1": "规格", + "v1": "1kg" + } + ] +} +``` + +响应只返回创建结果摘要,字段结构如下: + +```json +{ + "data": { + "item_id": 726390485721088000, + "title": "澳洲和牛家庭装" + }, + "success": true, + "code": 0, + "message": "success" +} +``` + +其中 `data.item_id` 是服务生成后的商品主键 ID,`data.title` 是商品标题。 + +### `GetProduct` + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `product_id` | `string` | 是 | 商品 SPU ID | + +响应 `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` + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `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 不传以查看全部状态 | + +分页响应字段: + +| 字段 | 类型 | 说明 | +|---|---|---| +| `products` | `Product[]` | 当前页商品列表 | +| `page` | `int32` | 当前页码 | +| `page_size` | `int32` | 当前每页数量 | +| `total` | `int64` | 分类/分组下商品总数 | +| `total_pages` | `int32` | 总页数 | + +`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` 渲染。 + +### `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[]` | 子分类列表 | + ## 技术栈 | 项 | 选型 | |---|---| | 语言 | 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 +185,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,9 +219,26 @@ 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` | 预留事件总线地址(首版查询链路不依赖) | +| `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 中的部署环境标签 | +| `SNOWFLAKE_WORKER_ID` | `1` | Snowflake worker ID;同一部署环境内不同服务实例必须使用不同值 | + +### 可观测性 + +| 能力 | 入口 / 指标 | 说明 | +|---|---|---| +| 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_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` | ### 构建与运行 @@ -85,25 +257,34 @@ 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":["",""]}' \ - localhost:50052 ids.product.v1.ProductService/BatchGetProducts +# 创建商品;product_id 和 sku_id 由服务生成 +grpcurl -plaintext -d '{"spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_INVENTORY","skus":[]}' \ + localhost:50052 ids.product.v1.ProductService/CreateProduct + +# 分页查询分类商品 +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 ``` ## 数据模型 -商品域采用 SPU/SKU 分层,**仅读写** `product_schema`: +商品域采用 SPU/SKU 分层,**仅读写** `product`: | 表 | 职责 | |---|---| -| `product_schema.products` | SPU 主表(名称、描述、状态、扩展属性) | -| `product_schema.skus` | SKU 明细(规格、价格、库存) | +| `product.products` | SPU 主表(标题、卖点、状态、扩展属性) | +| `product.product_items` | SKU 明细(规格、价格、属性) | +| `product.product_item_inventory` | SKU 库存销量(可售、锁定、已售) | - 价格字段统一为 `BIGINT` / Go `int64`,单位:**分** -- 禁止跨 Schema JOIN(`order_schema`、`user_schema` 等) +- 禁止跨 Schema JOIN(`trade`、`customer` 等) ## 架构约束 @@ -116,22 +297,10 @@ grpcurl -plaintext -d '{"product_ids":["",""]}' \ | ID | 约束 | |---|---| -| ARC-PROD-001 | 仅读写 `product_schema`,禁止跨 Schema JOIN | -| ARC-PROD-003 | `BatchGetProducts` 对重复 ID 去重,缺失 ID 静默跳过 | +| ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN | | ARC-PROD-004 | 价格字段统一 `int64`(分) | | ARC-PROD-005 | 状态枚举强对齐 `productv1.ProductStatus` | -## 与订单域协作 - -``` -ids-svc-order (算价) ──BatchGetProducts──▶ ids-svc-product - │ - ▼ - PG product_schema -``` - -订单服务通过 gRPC 批量拉取 SKU 价格,**不得**跨库查询商品表。 - ## 相关仓库 | 仓库 | 关系 | diff --git a/cmd/main.go b/cmd/main.go index 6394898..b97fb8a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,23 +4,31 @@ 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" + "go.uber.org/zap/zapcore" "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/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" ) func main() { - logger, err := zap.NewProduction() + logger, err := newLogger() if err != nil { panic(err) } @@ -31,9 +39,26 @@ 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() + 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 +77,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, idGenerator, 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 +114,20 @@ 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)) + } +} + +func newLogger() (*zap.Logger, error) { + cfg := zap.NewProductionConfig() + cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + return cfg.Build() } diff --git a/docker-compose.yaml b/docker-compose.yaml index 64cbd7e..c65f107 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -13,13 +13,19 @@ 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 + METRICS_PORT: ":9102" + 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: - "${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 3f9d6c0..4ac31a5 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.product_items` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 | 所有价格字段(如 `price`)统一采用 `BIGINT` / Go `int64`,单位为**分**。禁止使用 `float32`、`float64` 或数据库浮点类型表达金额。 @@ -49,7 +49,7 @@ │ ▼ ┌──────────────────────────────┐ - │ PG product_schema │ + │ PG product │ └──────────────────────────────┘ ``` @@ -59,28 +59,30 @@ |---|---|---| | 启动信宿 | `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.product_items` 的 CRUD 和批量查询能力。 | | 配置底座 | `internal/config/` | 轻量读取环境变量,优先加载本地 `.env`,生产环境无 `.env` 时静默降级到环境注入。 | --- ## 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 / 商城前台 | 根据分类/分组节点分页返回商品列表。 | +| `ListCategoryTree` | 微信小程序分类页 / BFF | 返回 `node_type = 0` 的商品分类树,子分类挂载在父分类 `children` 下。 | ### 3.2 查询实现约束 -1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product_schema.products` 与 `product_schema.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 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 +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 查询补齐分类展示信息。 --- @@ -91,8 +93,12 @@ | 环境变量 | 默认值 | 说明 | |---|---|---| | `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。 | +| `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 +116,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 与错误状态。 | --- @@ -124,8 +132,7 @@ 3. 数据库操作必须收敛在 `internal/repository` 层,**严禁**在 `internal/server` 抛出 naked SQL。 4. 严格按照 `ids-proto` 中 `ids.product.v1` / `productv1` 的结构体定义进行序列化与反序列化。 5. 商品状态枚举必须强对齐 `productv1.ProductStatus`,不得在 gRPC 响应中暴露内部字符串状态。 -6. 跨域数据(订单、用户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。 -7. `BatchGetProducts` 是订单算价链路的关键接口,应优先保证低延迟、批量查询与清晰错误语义。 +6. 跨域数据(订单、客户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。 --- @@ -133,9 +140,8 @@ | 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`,单位为分 | | ARC-PROD-005 | 状态枚举强对齐 `productv1` proto 枚举 | | ARC-PROD-006 | 配置加载优先 `.env`,生产无 `.env` 时静默降级 | diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index fe1feae..2b01ad8 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,8 +59,12 @@ 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 +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 可用性。 @@ -111,20 +119,18 @@ 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.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_schema` 内关联或分步查询。 +- **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `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. 校验必要字段; @@ -164,13 +170,12 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository |---|---| | 1 | 价格字段一律 `int64`(单位:分),**禁止** `float64` | | 2 | 状态枚举强对齐 `productv1.ProductStatus` | -| 3 | repository 仅操作 `product_schema.products` 与 `product_schema.skus` | +| 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 响应拼装 | --- @@ -190,10 +195,9 @@ 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] | | 商品状态枚举强对齐 proto | [ARC-PROD-005] | | 配置优先 `.env` 并支持生产静默降级 | [ARC-PROD-006] | -| 商品服务作为订单算价阶段商品事实来源 | [ADR-PROD-001] | +| 商品服务作为商品主数据事实来源 | [ADR-PROD-001] | 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..6b56fee --- /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 的 stock_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, + "stock_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`; +- `stock_quantity`; +- `status`; +- `image_ids`。 + +不能修改 `sku_no`、`k1/v1` 至 `k3/v3`、销量或锁定库存。`name` 可单独覆盖,不影响 SKU 编号和规格组合。`stock_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, + "stock_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, + "stock_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`;库存补充本身不会改变商品状态。 + +上架时必须存在至少一个启用、未归档且 `stock_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/go.mod b/go.mod index 04032c7..63ef309 100644 --- a/go.mod +++ b/go.mod @@ -5,23 +5,46 @@ 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 + 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/grpc v1.82.0 google.golang.org/protobuf v1.36.11 llms.idsbuybuybuy.com/ecommerce/ids-proto v0.0.0-00010101000000-000000000000 ) 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 - 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 + go.yaml.in/yaml/v2 v2.4.2 // 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 2012369..abd826b 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,15 @@ +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= 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= @@ -13,6 +20,8 @@ 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= @@ -23,8 +32,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= @@ -32,8 +61,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= @@ -42,33 +77,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/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/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-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/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= +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 967ca66..e75b906 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -10,21 +10,28 @@ 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" + 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/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/observability/observability.go b/internal/observability/observability.go new file mode 100644 index 0000000..f5bd91c --- /dev/null +++ b/internal/observability/observability.go @@ -0,0 +1,263 @@ +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.", + }, + ) + + productListsTotal = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: "ids", + Subsystem: "product", + Name: "product_lists_total", + Help: "Total number of successful all-product list queries.", + }, + ) + + 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", + Subsystem: "product", + Name: "category_tree_lists_total", + Help: "Total number of successful category tree 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() +} + +// IncProductLists records a successful all-product list query. +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() +} + +// 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/repository/product_repository.go b/internal/repository/product_repository.go index 0105019..9051dd6 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -6,43 +6,267 @@ import ( "encoding/json" "errors" "fmt" + "sort" + "strconv" "strings" "time" + "github.com/jackc/pgx/v5/pgconn" + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" ) // 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") +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") -// ProductRecord is the persistence model for product_schema.products (SPU). +// 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") + +// 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 - 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 + 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 + LeafCategoryIDs []string + CategoryBindingIDs []string + Version int32 + DeletedAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time } -// SKURecord is the persistence model for product_schema.skus. +// 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 - ProductID string - Name string - Price int64 - Stock int32 - AttributesJSONB string - CreatedAt time.Time - UpdatedAt time.Time + 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 } -// ProductRepository provides CRUD access to product_schema tables only [ARC-PROD-001]. +// InventoryRecord is the persistence model for product.product_item_inventory. +type InventoryRecord struct { + ID string + SKUID string + StockQuantity int32 + LockedQuantity int32 + SoldQuantity int32 + Version int32 + CreatedAt time.Time + 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 { + 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 + +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 + StockQuantity *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 + // 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. +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 + 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. +type CategoryRecord struct { + ID string + NodeType int32 + Name string + ParentID string + Level int32 + 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 + NewChildren []CategoryRecord +} + +// ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. type ProductRepository struct { db *sql.DB } @@ -52,48 +276,627 @@ 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'; +ALTER TABLE product.products + ALTER COLUMN id DROP DEFAULT; -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, +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[]; + +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 ( + 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, + 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), + 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 INDEX IF NOT EXISTS idx_skus_product_id ON product_schema.skus(product_id); +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), + 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), + 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 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 + ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; +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 { - return fmt.Errorf("ensure product_schema tables: %w", err) + return fmt.Errorf("ensure product tables: %w", err) } return nil } // CreateProduct inserts a new SPU row. func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRecord) error { - attrs, err := json.Marshal(product.Attrs) + attrs, err := productCrossBorderJSON(product) if err != nil { - return fmt.Errorf("marshal product attrs: %w", err) - } - if product.Attrs == nil { - attrs = []byte("{}") + return err } - _, err = r.db.ExecContext(ctx, ` -INSERT INTO product_schema.products (id, spu_code, title, description, status, attrs) -VALUES ($1, $2, $3, $4, $5, $6::jsonb) -`, product.ID, product.SPUCode, product.Name, product.Description, 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 := productCrossBorderJSON(product) + 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, product, attrs) + if err != nil { + return nil, nil, err + } + + createdSKUs := make([]SKURecord, 0, len(skus)) + for _, sku := range skus { + createdSKU, err := insertSKU(ctx, tx, createdProduct.ID, sku) + if err != nil { + return nil, nil, err + } + createdSKUs = append(createdSKUs, *createdSKU) + } + + if len(product.LeafCategoryIDs) > 0 { + if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs); err != nil { + return nil, nil, err + } + } + + if err := tx.Commit(); err != nil { + return nil, nil, fmt.Errorf("commit create product: %w", err) + } + + 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 +} + +// 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 != 1 || 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 != 1 || current.Level != 2 || current.ParentID != tree.CategoryID { + return ErrCategoryTreeConflict + } + if _, err := updateCategoryFields(ctx, tx, child); err != nil { + 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) + } + 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 { + 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 { + 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 +} + +// 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 } @@ -108,11 +911,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, selling_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.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) if err != nil { return fmt.Errorf("update product %s: %w", product.ID, err) } @@ -127,9 +935,476 @@ WHERE id = $1 return nil } -// DeleteProduct removes an SPU and its SKUs via ON DELETE CASCADE. +// 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.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 + } + + 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 +} + +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 { + 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.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 + 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.StockQuantity < lockedQuantity { + return fmt.Errorf("stock_quantity cannot be less than locked_quantity") + } + if _, err := tx.ExecContext(ctx, ` +UPDATE product.product_item_inventory +SET stock_quantity = $2, version = version + 1, updated_at = NOW() +WHERE sku_id = $1 AND version = $3 +`, skuID, *input.StockQuantity, 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.stock_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.stock_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 { - 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, ` +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) } @@ -141,38 +1416,84 @@ 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 } // 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 } - _, err = r.db.ExecContext(ctx, ` -INSERT INTO product_schema.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) + productID, err := parseID(sku.ProductID, "product id") if err != nil { - return fmt.Errorf("insert sku %s: %w", sku.ID, err) + return err + } + skuID, err := parseID(sku.ID, "sku id") + if err != nil { + return err + } + inventoryID, err := inventoryIDFromSKU(sku) + if err != nil { + return err + } + + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin create sku: %w", err) + } + defer tx.Rollback() + + err = tx.QueryRowContext(ctx, ` +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 +`, 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 := insertSKUInventory(ctx, tx, inventoryID, skuID, sku.StockQuantity); 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 } - res, err := r.db.ExecContext(ctx, ` -UPDATE product_schema.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, err := parseID(sku.ID, "sku id") + if err != nil { + return err + } + 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 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) } @@ -184,12 +1505,327 @@ WHERE id = $1 if affected == 0 { return ErrSKUNotFound } + + if _, err := updateSKUInventory(ctx, tx, id, sku.StockQuantity); err != nil { + return err + } + + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit update sku: %w", err) + } return nil } -// DeleteSKU removes a SKU row. +// 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") + } + id, err := parseID(skuID, "sku id") + if err != nil { + return nil, err + } + + 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 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) { + 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) + } + 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 +} + +// 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 := q.QueryRowContext(ctx, ` +SELECT EXISTS( + 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 { + 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 { - 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, ` +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) } @@ -215,36 +1851,460 @@ 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 } -// 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) +// 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 } - if len(products) == 0 { - return []*ProductRecord{}, map[string][]SKURecord{}, nil + 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 { + 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) { + if len(lookups) == 0 { + return []CartItemProductRecord{}, nil } - foundIDs := make([]string, 0, len(products)) + 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 { - foundIDs = append(foundIDs, product.ID) + productsByID[product.ID] = product + } + skusByID := make(map[string]*SKURecord, len(skus)) + for index := range skus { + skusByID[skus[index].ID] = &skus[index] } - skuMap, err := r.loadSKUsByProductIDs(ctx, foundIDs) + 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 { + 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), + 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.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 + 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 +LIMIT $1 OFFSET $2 +`, pageSize, offset) if err != nil { - return nil, nil, err + 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 +} + +// 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 } - return products, skuMap, nil + 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.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.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 + 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 + 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") + if err != nil { + return 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 p +JOIN product.product_category_bindings b ON b.product_id = p.id +WHERE b.category_id = $1 + AND p.deleted_at IS NULL + 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 { + 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.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.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 + 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 $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) + } + 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 category products: %w", err) + } + return products, 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, + node_type, + name, + parent_id, + level, + COALESCE(to_json(image_ids)::text, '[]'), + sort_num, + status, + version +FROM product.product_category +WHERE node_type = 1 + 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 +} + +// 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, + COALESCE(to_json(image_ids)::text, '[]'), + sort_num, + status, + version +FROM product.product_category +WHERE node_type = 2 + 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) { @@ -262,14 +2322,40 @@ 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(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, + version, + deleted_at, + created_at, + updated_at +FROM product.products WHERE id IN (%s) + AND deleted_at IS NULL ORDER BY created_at ASC `, strings.Join(placeholders, ", ")) @@ -294,6 +2380,270 @@ ORDER BY created_at ASC return products, nil } +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 + } + 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, + 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, $13::jsonb, $14, $15, $16, $17, $18) +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, + version, + deleted_at, + created_at, + updated_at +`, 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) + + 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 { + 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, sku_no, name, price, image_ids, attributes, status) +VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8) +RETURNING id, + product_id, + sku_no, + name, + price, + COALESCE(to_json(image_ids)::text, '[]'), + attributes, + status, + is_archived, + archived_at, + version, + deleted_at, + created_at, + updated_at, + NULL::bigint, + NULL::bigint, + 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)) + + createdSKU, err := scanSKU(row) + if err != nil { + return nil, fmt.Errorf("insert sku: %w", err) + } + + createdSKUID, err := parseID(createdSKU.ID, "sku id") + if err != nil { + return nil, err + } + inventoryID, err := inventoryIDFromSKU(sku) + if err != nil { + return nil, err + } + inventory, err := insertSKUInventory(ctx, tx, inventoryID, createdSKUID, sku.StockQuantity) + if err != nil { + return nil, err + } + createdSKU.Inventory = inventory + if inventory != nil { + createdSKU.StockQuantity = inventory.StockQuantity + createdSKU.LockedQuantity = inventory.LockedQuantity + createdSKU.SoldQuantity = inventory.SoldQuantity + } + return createdSKU, nil +} + +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 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, 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, 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) + } + return inventory, nil +} + +func updateSKUInventory(ctx context.Context, tx *sql.Tx, skuID int64, stockQuantity int32) (*InventoryRecord, error) { + row := tx.QueryRowContext(ctx, ` +UPDATE product.product_item_inventory +SET stock_quantity = $2, + version = version + 1, + updated_at = NOW() +WHERE sku_id = $1 +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) + } + 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 { + return err + } + 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 (id, product_id, category_id) +VALUES ($1, $2, $3) +ON CONFLICT (product_id, category_id) DO NOTHING +`, parsedBindingID, parsedProductID, parsedCategoryID) + if err != nil { + return fmt.Errorf("insert category binding: %w", err) + } + 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} + } + + row := tx.QueryRowContext(ctx, ` +INSERT INTO product.product_category ( + id, + node_type, + name, + parent_id, + level, + image_ids, + sort_num, + status +) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +RETURNING id, + node_type, + name, + parent_id, + level, + COALESCE(to_json(image_ids)::text, '[]'), + sort_num, + status, + version +`, 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 { + 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 { @@ -303,15 +2653,43 @@ 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 -WHERE product_id IN (%s) -ORDER BY created_at ASC +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.stock_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, ", ")) rows, err := r.db.QueryContext(ctx, query, args...) @@ -334,68 +2712,353 @@ ORDER BY 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.stock_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 } -func scanProduct(scanner rowScanner) (*ProductRecord, error) { +func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { var ( - rec ProductRecord - status string - attrsJSON []byte + rec CategoryProductRecord + id int64 + status int16 + imageIDsJSON string ) if err := scanner.Scan( - &rec.ID, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &rec.UpdatedAt, + &rec.CreatedAt, + &rec.Title, + &id, + &rec.SPUNo, + &status, + &imageIDsJSON, + &rec.Price, + &rec.SoldQuantity, + &rec.StockQuantity, + &rec.LockedQuantity, + ); 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 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 + version int32 + 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, + &version, + &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) + rec.Version = version + 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 - attrsJSON []byte + rec SKURecord + id int64 + productID int64 + skuNo sql.NullString + imageIDsJSON string + attrsJSON []byte + status int16 + isArchived bool + archivedAt sql.NullTime + version int32 + deletedAt sql.NullTime + inventoryID sql.NullInt64 + inventorySKUID sql.NullInt64 + stockQuantity sql.NullInt32 + lockedQuantity sql.NullInt32 + soldQuantity sql.NullInt32 + inventoryVersion sql.NullInt32 + inventoryCreatedAt sql.NullTime + inventoryUpdatedAt sql.NullTime ) if err := scanner.Scan( - &rec.ID, &rec.ProductID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt, + &id, + &productID, + &skuNo, + &rec.Name, + &rec.Price, + &imageIDsJSON, + &attrsJSON, + &status, + &isArchived, + &archivedAt, + &version, + &deletedAt, + &rec.CreatedAt, + &rec.UpdatedAt, + &inventoryID, + &inventorySKUID, + &stockQuantity, + &lockedQuantity, + &soldQuantity, + &inventoryVersion, + &inventoryCreatedAt, + &inventoryUpdatedAt, ); err != nil { return nil, fmt.Errorf("scan sku: %w", err) } - rec.AttributesJSONB = string(attrsJSON) - if rec.AttributesJSONB == "" { - rec.AttributesJSONB = "{}" + rec.ID = formatID(id) + rec.ProductID = formatID(productID) + 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 = "[]" + } + if err := applySKUAttributes(&rec); err != nil { + 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) + } + if inventoryID.Valid { + rec.Inventory = &InventoryRecord{ + 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 + } + if inventoryUpdatedAt.Valid { + rec.Inventory.UpdatedAt = inventoryUpdatedAt.Time + } + rec.StockQuantity = rec.Inventory.StockQuantity + rec.LockedQuantity = rec.Inventory.LockedQuantity + rec.SoldQuantity = rec.Inventory.SoldQuantity } 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) +func scanInventory(scanner rowScanner) (*InventoryRecord, error) { + var ( + rec InventoryRecord + id int64 + skuID int64 + ) + if err := scanner.Scan( + &id, + &skuID, + &rec.StockQuantity, + &rec.LockedQuantity, + &rec.SoldQuantity, + &rec.Version, + &rec.CreatedAt, + &rec.UpdatedAt, + ); err != nil { + return nil, fmt.Errorf("scan inventory: %w", err) } - return out + rec.ID = formatID(id) + rec.SKUID = formatID(skuID) + return &rec, nil +} + +func scanCategory(scanner rowScanner) (*CategoryRecord, error) { + var ( + 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, &imageIDsJSON, &rec.SortNum, &status, &rec.Version, + ); 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) + } + rec.Level = int32(level) + 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 } 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) @@ -403,28 +3066,185 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } -func statusToDB(status productv1.ProductStatus) string { +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 { + return nil + } + attrs, err := parseSKUAttributes(rec.AttributesJSON) + if err != nil { + return 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 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 + } + var values []string + if err := json.Unmarshal([]byte(raw), &values); err != nil { + return nil, err + } + 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 + } + 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: - return "draft" + case productv1.ProductStatus_PRODUCT_STATUS_INVENTORY: + return 1 case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE: - return "on_sale" + return 2 case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE: - return "off_sale" + return 3 default: - return "unspecified" + return 1 } } -func statusFromDB(status string) productv1.ProductStatus { +func statusFromDB(status int16) productv1.ProductStatus { switch status { - case "draft": - return productv1.ProductStatus_PRODUCT_STATUS_DRAFT - case "on_sale": + case 1: + return productv1.ProductStatus_PRODUCT_STATUS_INVENTORY + case 2: 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 } } + +// 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 { + 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) +} diff --git a/internal/repository/product_repository_test.go b/internal/repository/product_repository_test.go new file mode 100644 index 0000000..45de7b4 --- /dev/null +++ b/internal/repository/product_repository_test.go @@ -0,0 +1,39 @@ +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) + } +} + +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/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/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 603dff2..3f274ef 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -2,35 +2,133 @@ package server import ( "context" + "encoding/json" "errors" + "fmt" + "math" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" + "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" + "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" + "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" ) +const ( + defaultPageSize = int32(20) + maxPageSize = int32(100) + + categoryNodeType = int32(1) + groupNodeType = int32(2) + + defaultNodeStatus = int32(1) + maxNodeNameLength = 100 + maxProductsPerGroupRequest = 100 + maxCartItemProductBatchSize = 100 + maxSearchKeywordLength = 50 +) + // ProductServer implements productv1.ProductServiceServer. type ProductServer struct { productv1.UnimplementedProductServiceServer - repo *repository.ProductRepository - logger *zap.Logger + 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) *ProductServer { +func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer { if logger == nil { logger = zap.NewNop() } - return &ProductServer{ - repo: repo, - logger: logger, + if observer == nil { + observer = observability.NewNoop(logger) } + return &ProductServer{ + repo: repo, + idgen: idGenerator, + logger: logger, + observer: observer, + } +} + +// 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 { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + + product, skus, err := productFromCreateRequest(req) + 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() + skus[i].Inventory = &repository.InventoryRecord{ID: 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( + attribute.String("product.spu_no", product.SPUNo), + attribute.Int("product.sku_count", len(skus)), + )) + defer dbSpan.End() + + createdProduct, _, err := s.repo.CreateProductWithSKUs(dbCtx, product, skus) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("create product failed", zap.String("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) + } + 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() + + 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{ + Data: &productv1.CreateProductData{ + ItemId: itemID, + Title: createdProduct.Title, + }, + Success: true, + Code: 0, + Message: "success", + }, nil } // GetProduct returns a single SPU and its SKU list. @@ -39,12 +137,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) } @@ -53,28 +157,1619 @@ 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) { +// 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. +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() == "" { + 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() + 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, + LeafCategoryIDs: leafCategoryIDs, + CategoryBindingIDs: categoryBindingIDs, + }) + 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()) + 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) + } + } + + 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()) + + 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 +} + +// 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.ListCategoryProductsResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } - products, skuMap, err := s.repo.BatchGetProducts(ctx, req.GetProductIds()) + 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 { - 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) + 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.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)) } - return &productv1.BatchGetProductsResponse{ - Products: protoProducts, + return &productv1.ListCategoryProductsResponse{ + 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() == "" { + 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, 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()), + attribute.Int("page", int(page)), + attribute.Int("page_size", int(pageSize)), + )) + defer dbSpan.End() + + 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()) + 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.CategoryProduct, 0, len(products)) + for _, product := range products { + protoProducts = append(protoProducts, toProtoCategoryProduct(product)) + } + + return &productv1.ListCategoryProductsResponse{ + Products: protoProducts, + Page: page, + PageSize: pageSize, + Total: total, + TotalPages: totalPages(total, pageSize), + }, 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 +} + +// 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 + 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() + + resp := &productv1.ListCategoryTreeResponse{ + Categories: buildCategoryTree(categories), + } + 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. +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 +} + +// 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()) + } + 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 { + 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 +} + +// 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 { + 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 +} + +// 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 +} + +// 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() == "" { + 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.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: + 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 +} + +// 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 + } + pages := (total + int64(pageSize) - 1) / int64(pageSize) + if pages > math.MaxInt32 { + return math.MaxInt32 + } + 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 + } + imageIDs, err := normalizeNodeImageIDs(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, + ImageIDs: imageIDs, + 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{}{} + + childImageIDs, err := normalizeNodeImageIDs(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, + ImageIDs: childImageIDs, + SortNum: child.GetSortNum(), + Status: childStatus, + }) + } + + 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) + } + 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 }) + 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 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) + } + 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 { + return repository.CategoryRecord{}, err + } + imageIDs, err := normalizeNodeImageIDs(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, + ImageIDs: imageIDs, + 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 normalizeNodeImageIDs(raw string) ([]string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return []string{}, nil + } + 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 normalizeStringList(imageIDs), 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 == "" { + return repository.ProductRecord{}, nil, errors.New("spu_no is required") + } + + title := strings.TrimSpace(req.GetTitle()) + if title == "" { + return repository.ProductRecord{}, nil, errors.New("title is required") + } + + 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 { + return repository.ProductRecord{}, nil, errors.New("unsupported product status") + } + crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo()) + if err != nil { + return repository.ProductRecord{}, nil, err + } + + record := repository.ProductRecord{ + 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()), + } + 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") + } + 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(protoSKU) + if err != nil { + return repository.ProductRecord{}, nil, errors.New("skus[" + strconv.Itoa(i) + "]: " + err.Error()) + } + 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() + 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) + } + } + 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") + } + 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 "stock_quantity": + value := input.GetStockQuantity() + update.StockQuantity = &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.StockQuantity > sku.LockedQuantity { + return true + } + } + return false +} + +func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, error) { + if sku == nil { + return repository.SKURecord{}, errors.New("sku is required") + } + + if sku.GetPrice() < 0 { + return repository.SKURecord{}, errors.New("price 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) + if err != nil { + return repository.SKURecord{}, err + } + name := strings.TrimSpace(sku.GetName()) + if name == "" { + name = derivedName + } + statusValue := sku.GetStatus() + if statusValue < 0 || statusValue > 1 { + return repository.SKURecord{}, errors.New("status must be 0 or 1") + } + + return repository.SKURecord{ + 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 +} + +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, UseEnumNumbers: 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)) + seen := make(map[string]struct{}, len(values)) + for _, value := range values { + trimmed := strings.TrimSpace(value) + if trimmed == "" { + continue + } + if _, ok := seen[trimmed]; ok { + continue + } + seen[trimmed] = struct{}{} + out = append(out, trimmed) + } + 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 { + 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 + } + return value +} + +func timestampToTime(value *timestamppb.Timestamp) *time.Time { + if value == nil { + return nil + } + t := value.AsTime() + return &t +} + +func timeToMillisString(value time.Time) string { + return strconv.FormatInt(value.UnixMilli(), 10) +} + +func timePtrToMillisString(value *time.Time) *string { + if value == nil { + return nil + } + millis := timeToMillisString(*value) + return &millis +} + +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 @@ -83,22 +1778,207 @@ 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, + 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), }) } return &productv1.Product{ - ProductId: product.ID, - 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: timeToMillisString(product.CreatedAt), + UpdatedAt: timeToMillisString(product.UpdatedAt), + ImageIds: product.ImageIDs, + BrandId: product.BrandID, + SupplierId: product.SupplierID, + DetailHtml: product.DetailHTML, + MemberDiscountEnabled: product.MemberDiscountEnabled, + GoodsType: product.GoodsType, + ServiceGuarantees: product.ServiceGuarantees, + CrossBorderJson: product.CrossBorderJSON, + CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), + FreightChargeType: product.FreightChargeType, + FreightFixedAmount: product.FreightFixedAmount, + FreightTemplateId: product.FreightTemplateID, + SaleTimeType: product.SaleTimeType, + ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), + Version: product.Version, + DeletedAt: timePtrToMillisString(product.DeletedAt), + LeafCategoryIds: append([]string(nil), product.LeafCategoryIDs...), } } + +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.SkuStockQuantity = record.SKU.StockQuantity + 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 + } + 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, + StockQuantity: product.StockQuantity, + LockedQuantity: product.LockedQuantity, + } +} + +func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductItemInventory { + if inventory == nil { + return nil + } + return &productv1.ProductItemInventory{ + 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), + } +} + +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)) + orderedIDs := make([]string, 0, len(categories)) + + for _, category := range categories { + if category == nil || category.ID == "" { + continue + } + nodes[category.ID] = toProtoCategoryNode(category) + records[category.ID] = category + orderedIDs = append(orderedIDs, category.ID) + } + + roots := make([]*productv1.CategoryNode, 0) + for _, id := range orderedIDs { + node := nodes[id] + record := records[id] + if node == nil || record == nil { + continue + } + + parentID := record.ParentID + parent, parentExists := nodes[parentID] + parentRecord := records[parentID] + if parentID == "" || !parentExists || parentRecord == nil || parentID == id || parentRecord.Level >= record.Level { + roots = append(roots, node) + continue + } + + parent.Children = append(parent.Children, node) + } + + return roots +} + +func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.CategoryNode { + if category == nil { + return nil + } + return &productv1.CategoryNode{ + CategoryId: category.ID, + NodeType: category.NodeType, + Name: category.Name, + ParentId: category.ParentID, + Level: category.Level, + ImageJson: categoryImageIDsJSON(category.ImageIDs), + SortNum: category.SortNum, + Status: category.Status, + Version: category.Version, + 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: 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/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/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/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 new file mode 100644 index 0000000..c83d36f --- /dev/null +++ b/scripts/sql/recreate-product-tables.sql @@ -0,0 +1,260 @@ +-- 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 1, + 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 (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 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; + +CREATE TABLE IF NOT EXISTS product.product_category ( + id BIGINT PRIMARY KEY, + node_type SMALLINT NOT NULL DEFAULT 1, + name VARCHAR(100) NOT NULL, + parent_id BIGINT REFERENCES product.product_category(id), + level SMALLINT NOT NULL, + 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 (1, 2)), + CONSTRAINT chk_product_category_level + CHECK (level > 0), + CONSTRAINT chk_product_category_status + CHECK (status IN (0, 1)), + CONSTRAINT chk_product_category_version + CHECK (version >= 0) +); + +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 '节点类型: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'; +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); + +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), + 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(), + 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'; +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 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_active + 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 ( + 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), + 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), + 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 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 编码冗余字段,用于库存查询和对账'; +COMMENT ON COLUMN product.product_item_inventory.sku_no 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 '库存乐观锁版本号'; +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 + 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; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product; 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';