mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
Merge pull request 'Multi tenant' (#1) from multi-tenant into main
Reviewed-on: https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product/pulls/1
This commit is contained in:
commit
53631ed021
14
.dockerignore
Normal file
14
.dockerignore
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
.git
|
||||||
|
**/.git
|
||||||
|
**/.DS_Store
|
||||||
|
**/.env
|
||||||
|
**/.env.*
|
||||||
|
!**/.env.example
|
||||||
|
|
||||||
|
ids-svc-product/docs
|
||||||
|
ids-svc-product/.gitea
|
||||||
|
ids-svc-product/docker-compose.yaml
|
||||||
|
ids-svc-product/**/*_test.go
|
||||||
|
|
||||||
|
ids-proto/docs
|
||||||
|
ids-proto/.git
|
||||||
@ -7,7 +7,6 @@ POSTGRES_DB=ids_ecommerce
|
|||||||
POSTGRES_SCHEMA=product
|
POSTGRES_SCHEMA=product
|
||||||
POSTGRES_SSLMODE=disable
|
POSTGRES_SSLMODE=disable
|
||||||
NATS_URL=nats://localhost:4222
|
NATS_URL=nats://localhost:4222
|
||||||
|
|
||||||
METRICS_PORT=:9102
|
METRICS_PORT=:9102
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
|
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
|
||||||
OTEL_EXPORTER_OTLP_INSECURE=true
|
OTEL_EXPORTER_OTLP_INSECURE=true
|
||||||
|
|||||||
74
.gitea/workflows/ci.yml
Normal file
74
.gitea/workflows/ci.yml
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
name: Build & Deploy
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- multi-tenant
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
IMAGE: ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product
|
||||||
|
IMAGE_TAG: ${{ gitea.sha }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout Product
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
path: ids-svc-product
|
||||||
|
|
||||||
|
- name: Checkout Proto
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
repository: ids-ecommerce/ids-proto
|
||||||
|
ref: multi-tenant
|
||||||
|
path: ids-proto
|
||||||
|
token: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
- name: Prepare Docker ignorefile
|
||||||
|
run: cp ids-svc-product/.dockerignore .dockerignore
|
||||||
|
|
||||||
|
- name: Login Registry
|
||||||
|
run: |
|
||||||
|
echo "${{ secrets.REGISTRY_TOKEN }}" | \
|
||||||
|
docker login ids-dev.idsbuybuybuy.com \
|
||||||
|
-u "${{ secrets.REGISTRY_USER }}" \
|
||||||
|
--password-stdin
|
||||||
|
|
||||||
|
- name: Build Image
|
||||||
|
run: |
|
||||||
|
docker build \
|
||||||
|
-f ids-svc-product/Dockerfile \
|
||||||
|
-t "${IMAGE}:${IMAGE_TAG}" \
|
||||||
|
.
|
||||||
|
|
||||||
|
- name: Push Image
|
||||||
|
run: |
|
||||||
|
docker push "${IMAGE}:${IMAGE_TAG}"
|
||||||
|
|
||||||
|
- name: Configure SSH
|
||||||
|
run: |
|
||||||
|
mkdir -p ~/.ssh
|
||||||
|
chmod 700 ~/.ssh
|
||||||
|
|
||||||
|
printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" \
|
||||||
|
> ~/.ssh/ids_deploy
|
||||||
|
|
||||||
|
chmod 600 ~/.ssh/ids_deploy
|
||||||
|
|
||||||
|
ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" \
|
||||||
|
>> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
- name: Deploy
|
||||||
|
run: |
|
||||||
|
ssh \
|
||||||
|
-i ~/.ssh/ids_deploy \
|
||||||
|
"${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" \
|
||||||
|
"
|
||||||
|
set -e
|
||||||
|
|
||||||
|
cd /opt/ids-ecommerce
|
||||||
|
|
||||||
|
./deploy-service.sh ids-svc-product '${IMAGE_TAG}'
|
||||||
|
"
|
||||||
34
Dockerfile
Normal file
34
Dockerfile
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# Build from the parent directory that contains both ids-svc-product/ and ids-proto/:
|
||||||
|
# docker build -f ids-svc-product/Dockerfile -t ids-svc-product:local .
|
||||||
|
#
|
||||||
|
# go.mod replace points at ../ids-proto, so both trees must be present in the context.
|
||||||
|
|
||||||
|
FROM golang:1.26.4-alpine AS builder
|
||||||
|
|
||||||
|
RUN apk add --no-cache ca-certificates git
|
||||||
|
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
|
COPY ids-proto /src/ids-proto
|
||||||
|
COPY ids-svc-product/go.mod ids-svc-product/go.sum /src/ids-svc-product/
|
||||||
|
|
||||||
|
WORKDIR /src/ids-svc-product
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
COPY ids-svc-product/ /src/ids-svc-product/
|
||||||
|
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/ids-svc-product ./cmd
|
||||||
|
|
||||||
|
FROM alpine:3.21
|
||||||
|
|
||||||
|
RUN apk add --no-cache ca-certificates tzdata \
|
||||||
|
&& adduser -D -H -u 10001 appuser
|
||||||
|
|
||||||
|
COPY --from=builder /out/ids-svc-product /usr/local/bin/ids-svc-product
|
||||||
|
COPY --from=builder /src/ids-svc-product/scripts/sql/008_product_presale_delivery_purchase_limit.sql /app/migrations/008_product_presale_delivery_purchase_limit.sql
|
||||||
|
|
||||||
|
USER appuser
|
||||||
|
|
||||||
|
EXPOSE 50052 9102
|
||||||
|
|
||||||
|
ENTRYPOINT ["/usr/local/bin/ids-svc-product"]
|
||||||
46
README.md
46
README.md
@ -32,13 +32,15 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
| `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU |
|
| `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU |
|
||||||
| `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 |
|
| `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 |
|
||||||
| `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 |
|
| `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 |
|
||||||
|
| `AddProductsToGroup` | `POST /v1/categories/{category_id}/products` | `AddProductsToGroupRequest` | `AddProductsToGroupResponse` | 批量绑定商品到二级分类 |
|
||||||
|
| `AddProductsToGroup` | `POST /v1/groups/{group_id}` | `AddProductsToGroupRequest` | `AddProductsToGroupResponse` | 批量绑定商品到商品分组 |
|
||||||
| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 |
|
| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 |
|
||||||
|
|
||||||
### `CreateProduct`
|
### `CreateProduct`
|
||||||
|
|
||||||
创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。
|
创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。
|
||||||
|
|
||||||
当前创建接口不再接收 `product_id`、`sku_id`、`inventory_id` 和 SKU `name`:`product_id`、`sku_id`、`inventory_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。
|
当前创建接口不接收 `product_id`、`sku_id`、`inventory_id`:这些 ID 均由商品服务应用层生成雪花 ID。SKU `name` 可显式传入;未传时由后端按规格值 `v1/v2/v3` 拼接。
|
||||||
|
|
||||||
创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成:
|
创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成:
|
||||||
|
|
||||||
@ -48,24 +50,26 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` |
|
| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` |
|
||||||
| `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` |
|
| `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` |
|
||||||
| 分类绑定 ID | 每个 `leaf_category_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
| 分类绑定 ID | 每个 `leaf_category_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
||||||
|
| 分组绑定 ID | 每个 `group_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
||||||
|
|
||||||
常用请求字段:
|
常用请求字段:
|
||||||
|
|
||||||
| 字段 | 必填 | 说明 |
|
| 字段 | 必填 | 说明 |
|
||||||
|---|---:|---|
|
|---|---:|---|
|
||||||
| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 |
|
| `spu_no` | 否 | 商品业务编码;空值可重复,非空值在当前店铺未删除商品中唯一 |
|
||||||
| `title` | 是 | 商品标题 |
|
| `title` | 是 | 商品标题 |
|
||||||
| `selling_point` | 否 | 商品卖点 |
|
| `selling_point` | 否 | 商品卖点 |
|
||||||
| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 |
|
| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 |
|
||||||
|
| `group_ids` | 否 | 已存在的商品分组 ID 列表;传入后会写入全部商品分组绑定 |
|
||||||
| `image_ids` | 否 | 商品图片 ID 列表 |
|
| `image_ids` | 否 | 商品图片 ID 列表 |
|
||||||
| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID |
|
| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID |
|
||||||
| `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`OFF_SALE` |
|
| `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`SOLD_OUT`。其中 `SOLD_OUT` 的数值 `3` 业务语义为“已售罄”,可保留真实库存但拒绝新锁库。 |
|
||||||
| `goods_type` | 否 | 未传时默认 `1` |
|
| `goods_type` | 否 | 未传时默认 `1` |
|
||||||
| `freight_charge_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `freight_template_id` |
|
| `freight_charge_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `freight_template_id` |
|
||||||
| `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` |
|
| `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` |
|
||||||
| `skus` | 否 | SKU 列表 |
|
| `skus` | 否 | SKU 列表 |
|
||||||
|
|
||||||
`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。
|
`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。`sku_no` 和 `name` 均可为空或重复,SKU 主键才是唯一标识。
|
||||||
|
|
||||||
最小示例:
|
最小示例:
|
||||||
|
|
||||||
@ -75,6 +79,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
"title": "澳洲和牛家庭装",
|
"title": "澳洲和牛家庭装",
|
||||||
"selling_point": "原切谷饲,冷链到家",
|
"selling_point": "原切谷饲,冷链到家",
|
||||||
"leaf_category_ids": ["726390485721088000"],
|
"leaf_category_ids": ["726390485721088000"],
|
||||||
|
"group_ids": ["726390485721088001"],
|
||||||
"skus": [
|
"skus": [
|
||||||
{
|
{
|
||||||
"sku_no": "SKU20260710000101",
|
"sku_no": "SKU20260710000101",
|
||||||
@ -118,7 +123,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
|
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
|
||||||
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
|
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
|
||||||
|
|
||||||
返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。
|
返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。该接口额外批量回填每个商品直接绑定的标准类目(含直属父节点和根至当前节点完整路径)、商品分组及当前可用品牌展示信息;无类目/分组时返回空数组,无品牌时返回空值。`ListCategoryProducts` 和 `SearchProducts` 不填充这些后台列表展示字段。
|
||||||
|
|
||||||
### `ListCategoryProducts`
|
### `ListCategoryProducts`
|
||||||
|
|
||||||
@ -127,7 +132,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
| `category_id` | `string` | 是 | 分类/分组节点 ID,对应 `product.product_category.id` |
|
| `category_id` | `string` | 是 | 分类/分组节点 ID,对应 `product.product_category.id` |
|
||||||
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
|
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
|
||||||
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
|
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
|
||||||
| `only_visible` | `bool` | 否 | 为 `true` 时返回 `ON_SALE` 和 `OFF_SALE` 商品;小程序 BFF 固定传 `true`,Admin 不传以查看全部状态 |
|
| `only_visible` | `bool` | 否 | 为 `true` 时返回 `ON_SALE` 和 `SOLD_OUT` 商品;小程序 BFF 固定传 `true`,Admin 不传以查看全部状态 |
|
||||||
|
|
||||||
分页响应字段:
|
分页响应字段:
|
||||||
|
|
||||||
@ -139,11 +144,11 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类
|
|||||||
| `total` | `int64` | 分类/分组下商品总数 |
|
| `total` | `int64` | 分类/分组下商品总数 |
|
||||||
| `total_pages` | `int32` | 总页数 |
|
| `total_pages` | `int32` | 总页数 |
|
||||||
|
|
||||||
`products[]` 返回商品摘要以及全部未归档 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。
|
`products[]` 返回商品摘要以及全部未归档 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。状态 `3` 的消费者侧库存投影由 BFF 处理;商品服务仍保留真实账实。
|
||||||
|
|
||||||
### `UpdateProduct` 与 `UpdateProductStatus`
|
### `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`,补库存不会自动上架。
|
完整的输入输出及状态/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` 或 `SOLD_OUT`(数值 `3`,已售罄)状态执行,并归档而不删除旧 SKU(即使存在锁定库存)。库存耗尽仅会自动将 `ON_SALE` 转为 `SOLD_OUT`(已售罄),补库存不会自动恢复销售。
|
||||||
|
|
||||||
`products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
|
`products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
|
||||||
|
|
||||||
@ -190,11 +195,34 @@ ids-svc-product/
|
|||||||
├── docs/
|
├── docs/
|
||||||
│ ├── ARCHITECTURE.md # 架构白皮书
|
│ ├── ARCHITECTURE.md # 架构白皮书
|
||||||
│ └── DEVELOPMENT.md # 开发规约与 AI 生成指令
|
│ └── DEVELOPMENT.md # 开发规约与 AI 生成指令
|
||||||
|
├── Dockerfile # 生产镜像(需与 ids-proto 同级 context)
|
||||||
├── .env.example
|
├── .env.example
|
||||||
├── go.mod
|
├── go.mod
|
||||||
└── AGENTS.md
|
└── AGENTS.md
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## CI / Deploy(Gitea Actions)
|
||||||
|
|
||||||
|
`multi-tenant` 推送触发 [`.gitea/workflows/ci.yml`](.gitea/workflows/ci.yml):构建并推送镜像,再 SSH 滚动远端 compose。
|
||||||
|
|
||||||
|
本地/CI 构建(context 必须同时包含 `ids-svc-product/` 与 `ids-proto/`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在两仓的父目录执行
|
||||||
|
cp ids-svc-product/.dockerignore .dockerignore
|
||||||
|
docker build -f ids-svc-product/Dockerfile \
|
||||||
|
-t ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product:<sha> \
|
||||||
|
.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Gitea Secrets(建议配在组织级):** `REGISTRY_USER`、`REGISTRY_TOKEN`、`DEPLOY_SSH_KEY`、`DEPLOY_HOST`、`DEPLOY_USER`。
|
||||||
|
|
||||||
|
**远端 `/opt/ids-ecommerce` 前置(本仓不维护):**
|
||||||
|
|
||||||
|
- `.env` 含 `IDS_SVC_PRODUCT_TAG=` 行(流水线用 `sed` 替换为 `${{ gitea.sha }}`)
|
||||||
|
- `docker compose` 服务名 `ids-svc-product`,镜像引用该 tag
|
||||||
|
- Runner 可 `checkout` 同实例仓库 `ids-ecommerce/ids-proto`
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
### 前置依赖
|
### 前置依赖
|
||||||
@ -248,7 +276,7 @@ go build ./...
|
|||||||
go run ./cmd
|
go run ./cmd
|
||||||
```
|
```
|
||||||
|
|
||||||
启动时会执行 `db.PingContext()` 校验数据库连通性,并通过 `EnsureSchema` 补齐 `skus` 表及 `products` 扩展列。
|
启动时会执行 `db.PingContext()` 校验数据库连通性;随后执行 `scripts/sql/008_product_presale_delivery_purchase_limit.sql`(生产镜像内路径为 `/app/migrations/`)并通过 `EnsureSchema` 补齐 `skus` 表及其他 `products` 扩展列。该预售迁移使用 PostgreSQL advisory lock 串行化多副本启动,SQL 本身可重复执行;迁移失败时服务不会开始监听端口。
|
||||||
|
|
||||||
### 本地联调(grpcurl)
|
### 本地联调(grpcurl)
|
||||||
|
|
||||||
|
|||||||
16
cmd/main.go
16
cmd/main.go
@ -2,14 +2,12 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
_ "github.com/jackc/pgx/v5/stdlib"
|
|
||||||
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"go.uber.org/zap/zapcore"
|
"go.uber.org/zap/zapcore"
|
||||||
@ -21,6 +19,7 @@ import (
|
|||||||
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
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/config"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/postgresutc"
|
||||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen"
|
"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/observability"
|
||||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
@ -59,7 +58,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
db, err := sql.Open("pgx", cfg.PostgresDSN)
|
db, err := postgresutc.Open(cfg.PostgresDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Fatal("open postgres failed", zap.Error(err))
|
logger.Fatal("open postgres failed", zap.Error(err))
|
||||||
}
|
}
|
||||||
@ -73,6 +72,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
repo := repository.NewProductRepository(db)
|
repo := repository.NewProductRepository(db)
|
||||||
|
if err := repository.ApplyProductPresaleMigration(ctx, db); err != nil {
|
||||||
|
logger.Fatal("apply product presale migration failed", zap.Error(err))
|
||||||
|
}
|
||||||
if err := repo.EnsureSchema(ctx); err != nil {
|
if err := repo.EnsureSchema(ctx); err != nil {
|
||||||
logger.Fatal("ensure product schema failed", zap.Error(err))
|
logger.Fatal("ensure product schema failed", zap.Error(err))
|
||||||
}
|
}
|
||||||
@ -87,15 +89,18 @@ func main() {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
productServer := server.NewProductServer(repo, idGenerator, logger, observer)
|
productServer := server.NewProductServer(repo, idGenerator, logger, observer)
|
||||||
|
server.StartScheduledSaleWorker(ctx, repo, logger, time.Minute)
|
||||||
|
|
||||||
grpcServer := grpc.NewServer(
|
grpcServer := grpc.NewServer(
|
||||||
grpc.StatsHandler(otelgrpc.NewServerHandler()),
|
grpc.StatsHandler(otelgrpc.NewServerHandler()),
|
||||||
grpc.UnaryInterceptor(observer.UnaryServerInterceptor()),
|
grpc.UnaryInterceptor(observer.UnaryServerInterceptor()),
|
||||||
)
|
)
|
||||||
productv1.RegisterProductServiceServer(grpcServer, productServer)
|
productv1.RegisterProductServiceServer(grpcServer, productServer)
|
||||||
|
productv1.RegisterProductCategoryServiceServer(grpcServer, productServer)
|
||||||
healthServer := health.NewServer()
|
healthServer := health.NewServer()
|
||||||
healthServer.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)
|
healthServer.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)
|
||||||
healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_SERVING)
|
healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_SERVING)
|
||||||
|
healthServer.SetServingStatus(productv1.ProductCategoryService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_SERVING)
|
||||||
healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_SERVING)
|
healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_SERVING)
|
||||||
healthpb.RegisterHealthServer(grpcServer, healthServer)
|
healthpb.RegisterHealthServer(grpcServer, healthServer)
|
||||||
reflection.Register(grpcServer)
|
reflection.Register(grpcServer)
|
||||||
@ -117,6 +122,7 @@ func main() {
|
|||||||
|
|
||||||
healthServer.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING)
|
healthServer.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING)
|
||||||
healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
|
healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
|
||||||
|
healthServer.SetServingStatus(productv1.ProductCategoryService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
|
||||||
healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
|
healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
|
||||||
grpcServer.GracefulStop()
|
grpcServer.GracefulStop()
|
||||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
@ -128,6 +134,8 @@ func main() {
|
|||||||
|
|
||||||
func newLogger() (*zap.Logger, error) {
|
func newLogger() (*zap.Logger, error) {
|
||||||
cfg := zap.NewProductionConfig()
|
cfg := zap.NewProductionConfig()
|
||||||
cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
cfg.EncoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
|
||||||
|
enc.AppendString(t.UTC().Format(time.RFC3339Nano))
|
||||||
|
}
|
||||||
return cfg.Build()
|
return cfg.Build()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,13 +8,14 @@
|
|||||||
|
|
||||||
## 1. 业务域边界与数据隔离 (Bounded Context)
|
## 1. 业务域边界与数据隔离 (Bounded Context)
|
||||||
|
|
||||||
本服务是 IDS 电商矩阵中承载商品主数据、SKU 售卖信息与价格读取能力的基础服务。它为交易链路提供稳定的商品快照查询能力,尤其服务于 `ids-svc-order` 在提单与算价阶段对商品、SKU、价格和状态的同步读取。
|
本服务是 IDS 电商矩阵中承载商品主数据、SKU 售卖信息、SKU 基础价、库存、`member_discount_enabled` 和运费事实的基础服务。它为交易链路提供稳定的商品快照查询能力,由 BFF/API 聚合层在 Quote 或 Checkout 前读取并注入 `ids-svc-order`。
|
||||||
|
|
||||||
### 1.1 数据隔离红线 [ARC-PROD-001]
|
### 1.1 数据隔离红线 [ARC-PROD-001]
|
||||||
|
|
||||||
- 本服务**仅允许**读写 PostgreSQL 中的 `product`。
|
- 本服务**仅允许**读写 PostgreSQL 中的 `product`。
|
||||||
- 绝对禁止跨 Schema 去 `JOIN` `trade`、`customer` 或任何其他业务 Schema 的表。
|
- 绝对禁止跨 Schema 去 `JOIN` `trade`、`customer` 或任何其他业务 Schema 的表。
|
||||||
- 任何关于订单状态、客户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。
|
- 任何关于订单状态、客户会员权益、支付结果等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。
|
||||||
|
- 商品表只保存 SKU 基础价、库存、`member_discount_enabled` 和运费事实;会员折扣率、积分规则、券和满减规则不得写入商品表。
|
||||||
|
|
||||||
### 1.2 数据模型 (PostgreSQL)
|
### 1.2 数据模型 (PostgreSQL)
|
||||||
|
|
||||||
@ -66,7 +67,7 @@
|
|||||||
|
|
||||||
## 3. 商品查询契约 [ADR-PROD-001]
|
## 3. 商品查询契约 [ADR-PROD-001]
|
||||||
|
|
||||||
商品服务是商品 SPU/SKU 主数据与分类商品查询的事实来源。其他服务不允许跨 Schema 查询商品表。
|
商品服务是商品 SPU/SKU 主数据、SKU 基础价、库存、会员折扣开关与运费事实的来源。其他服务不允许跨 Schema 查询商品表;Quote 由 BFF 注入商品快照后在订单域计算,见 [ORDER_QUOTE.md](../../ids-svc-order/docs/ORDER_QUOTE.md)。
|
||||||
|
|
||||||
### 3.1 核心 RPC
|
### 3.1 核心 RPC
|
||||||
|
|
||||||
@ -83,6 +84,7 @@
|
|||||||
2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。
|
2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。
|
||||||
3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。
|
3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。
|
||||||
4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。
|
4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。
|
||||||
|
5. **[ARC-PROD-008] 会员折扣边界:** 商品域只保存 `member_discount_enabled` 开关,不保存会员折扣率;折扣率由 `ids-svc-customer` 的会员快照提供,最终叠加由 `ids-svc-order` Quote 计算。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -145,4 +147,5 @@
|
|||||||
| ARC-PROD-004 | 价格字段统一 `int64`,单位为分 |
|
| ARC-PROD-004 | 价格字段统一 `int64`,单位为分 |
|
||||||
| ARC-PROD-005 | 状态枚举强对齐 `productv1` proto 枚举 |
|
| ARC-PROD-005 | 状态枚举强对齐 `productv1` proto 枚举 |
|
||||||
| ARC-PROD-006 | 配置加载优先 `.env`,生产无 `.env` 时静默降级 |
|
| ARC-PROD-006 | 配置加载优先 `.env`,生产无 `.env` 时静默降级 |
|
||||||
|
| ARC-PROD-008 | 商品域只保存会员折扣开关,不保存折扣率 |
|
||||||
| ADR-PROD-001 | 商品服务作为订单算价阶段的商品事实来源 |
|
| ADR-PROD-001 | 商品服务作为订单算价阶段的商品事实来源 |
|
||||||
|
|||||||
@ -20,8 +20,8 @@
|
|||||||
| 数据库存储值 | Proto / API 枚举 | 含义 | 小程序行为 |
|
| 数据库存储值 | Proto / API 枚举 | 含义 | 小程序行为 |
|
||||||
|---:|---|---|---|
|
|---:|---|---|---|
|
||||||
| `1` | `PRODUCT_STATUS_INVENTORY` | 在仓库 | 不展示、不可购买 |
|
| `1` | `PRODUCT_STATUS_INVENTORY` | 在仓库 | 不展示、不可购买 |
|
||||||
| `2` | `PRODUCT_STATUS_ON_SALE` | 已上架 | 展示、可购买 |
|
| `2` | `PRODUCT_STATUS_ON_SALE` | 在销售 | 展示、可购买 |
|
||||||
| `3` | `PRODUCT_STATUS_OFF_SALE` | 已售罄 | 展示已售罄状态、不可购买 |
|
| `3` | `PRODUCT_STATUS_SOLD_OUT` | 已售罄 | 展示已售罄状态、不可购买 |
|
||||||
|
|
||||||
Proto 定义:
|
Proto 定义:
|
||||||
|
|
||||||
@ -29,7 +29,7 @@ Proto 定义:
|
|||||||
enum ProductStatus {
|
enum ProductStatus {
|
||||||
PRODUCT_STATUS_INVENTORY = 1;
|
PRODUCT_STATUS_INVENTORY = 1;
|
||||||
PRODUCT_STATUS_ON_SALE = 2;
|
PRODUCT_STATUS_ON_SALE = 2;
|
||||||
PRODUCT_STATUS_OFF_SALE = 3;
|
PRODUCT_STATUS_SOLD_OUT = 3;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -39,14 +39,14 @@ enum ProductStatus {
|
|||||||
INVENTORY -> ON_SALE
|
INVENTORY -> ON_SALE
|
||||||
运营人员上架;至少存在一个可售 SKU。
|
运营人员上架;至少存在一个可售 SKU。
|
||||||
|
|
||||||
ON_SALE -> OFF_SALE
|
ON_SALE -> SOLD_OUT
|
||||||
所有当前可售 SKU 的 stock_quantity - locked_quantity <= 0 时系统自动下架,
|
所有当前可售 SKU 的 stock_quantity - locked_quantity <= 0 时系统自动标记已售罄,
|
||||||
或由运营人员主动下架。
|
或由运营人员主动标记已售罄。状态 3 优先于真实库存,且不改写库存账实。
|
||||||
|
|
||||||
OFF_SALE -> ON_SALE
|
SOLD_OUT -> ON_SALE
|
||||||
仅由运营人员主动重新上架;补货不会自动恢复上架。
|
仅由运营人员主动恢复销售;补货不会自动恢复销售。
|
||||||
|
|
||||||
ON_SALE 或 OFF_SALE -> INVENTORY
|
ON_SALE 或 SOLD_OUT -> INVENTORY
|
||||||
运营人员放回仓库。
|
运营人员放回仓库。
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -179,7 +179,7 @@ SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。
|
|||||||
5. 禁止为已归档 SKU 创建新的库存锁定;
|
5. 禁止为已归档 SKU 创建新的库存锁定;
|
||||||
6. 商品版本递增,并重新计算商品是否自动售罄。
|
6. 商品版本递增,并重新计算商品是否自动售罄。
|
||||||
|
|
||||||
仅在商品处于 `INVENTORY` 或 `OFF_SALE` 时允许 `REPLACE_ALL`;商品为 `ON_SALE` 时必须返回冲突错误,避免上架中替换规格影响购物车和下单。
|
仅在商品处于 `INVENTORY` 或 `SOLD_OUT` 时允许 `REPLACE_ALL`;商品为 `ON_SALE` 时必须返回冲突错误,避免上架中替换规格影响购物车和下单。
|
||||||
|
|
||||||
成功响应:
|
成功响应:
|
||||||
|
|
||||||
@ -224,7 +224,7 @@ Content-Type: application/json
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
运营人员可以提交 `INVENTORY`、`ON_SALE`、`OFF_SALE`。无论商品是运营人员手动下架,还是因无可售库存自动切换为 `OFF_SALE`,都只能通过本接口显式重新设置为 `ON_SALE`;库存补充本身不会改变商品状态。
|
运营人员可以提交 `INVENTORY`、`ON_SALE`、`SOLD_OUT`。`SOLD_OUT` 是数值 `3` 的 protobuf 枚举名称,业务含义为“已售罄”。无论商品是运营人员手动标记已售罄,还是因无可售库存自动切换为 `SOLD_OUT`,都只能通过本接口显式重新设置为 `ON_SALE`;库存补充本身不会改变商品状态。设置为已售罄不会清空真实库存或锁定库存,但新锁库会被拒绝。
|
||||||
|
|
||||||
上架时必须存在至少一个启用、未归档且 `stock_quantity > locked_quantity` 的 SKU。
|
上架时必须存在至少一个启用、未归档且 `stock_quantity > locked_quantity` 的 SKU。
|
||||||
|
|
||||||
@ -232,7 +232,7 @@ Content-Type: application/json
|
|||||||
{
|
{
|
||||||
"product_id": "726390485721088003",
|
"product_id": "726390485721088003",
|
||||||
"previous_status": "PRODUCT_STATUS_ON_SALE",
|
"previous_status": "PRODUCT_STATUS_ON_SALE",
|
||||||
"status": "PRODUCT_STATUS_OFF_SALE",
|
"status": "PRODUCT_STATUS_SOLD_OUT",
|
||||||
"version": 14,
|
"version": 14,
|
||||||
"updated_at": "1754388000000"
|
"updated_at": "1754388000000"
|
||||||
}
|
}
|
||||||
@ -261,27 +261,17 @@ SKU 协议需要增加 `is_archived`、`archived_at` 与版本字段。普通接
|
|||||||
|---:|---|---:|---|
|
|---:|---|---:|---|
|
||||||
| `0` | DRAFT | `1` | INVENTORY |
|
| `0` | DRAFT | `1` | INVENTORY |
|
||||||
| `1` | ON_SALE | `2` | ON_SALE |
|
| `1` | ON_SALE | `2` | ON_SALE |
|
||||||
| `3` | OFF_SALE | `3` | OFF_SALE |
|
| `3` | SOLD_OUT | `3` | SOLD_OUT |
|
||||||
| `2` | 当前无有效语义 | `1` | INVENTORY |
|
| `2` | 当前无有效语义 | `1` | INVENTORY |
|
||||||
|
|
||||||
迁移后,`status` 默认值为 `1`,约束为 `status IN (1, 2, 3)`。
|
迁移后,`status` 默认值为 `1`,约束为 `status IN (1, 2, 3)`。
|
||||||
|
|
||||||
SKU 编号唯一索引只约束当前有效 SKU:
|
SKU 编号不建立唯一索引。`sku_no` 和 SKU 名称均为业务展示字段,可在同一店铺的当前 SKU 中重复;所有库存、更新和订单关联均使用 SKU 主键。
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE UNIQUE INDEX uq_product_items_sku_no_active
|
|
||||||
ON product.product_items (sku_no)
|
|
||||||
WHERE sku_no IS NOT NULL
|
|
||||||
AND deleted_at IS NULL
|
|
||||||
AND is_archived = FALSE;
|
|
||||||
```
|
|
||||||
|
|
||||||
必须先创建新索引,再删除旧 `uq_product_items_sku_no` 索引;否则归档 SKU 仍会阻止复用原 `sku_no`。
|
|
||||||
|
|
||||||
## 6. 实施位置
|
## 6. 实施位置
|
||||||
|
|
||||||
- `ids-proto/proto/ids/product/v1/product.proto`:状态枚举、SKU 归档字段、版本字段、更新 RPC 与消息;
|
- `ids-proto/proto/ids/product/v1/product.proto`:状态枚举、SKU 归档字段、版本字段、更新 RPC 与消息;
|
||||||
- `ids-svc-product/internal/repository/product_repository.go`:状态映射、归档字段、SKU 替换,以及仅在已上架商品无可售库存时自动下架的计算;
|
- `ids-svc-product/internal/repository/product_repository.go`:状态映射、归档字段、SKU 替换,以及仅在在销售商品无可售库存时自动标记已售罄的计算;
|
||||||
- `ids-svc-product/internal/server/product_server.go`:更新校验、状态流转与 gRPC 错误映射;
|
- `ids-svc-product/internal/server/product_server.go`:更新校验、状态流转与 gRPC 错误映射;
|
||||||
- `ids-svc-product` SQL 初始化、重建和正式迁移脚本:字段、约束和索引;
|
- `ids-svc-product` SQL 初始化、重建和正式迁移脚本:字段、约束和索引;
|
||||||
- `ids-admin-api/internal/handler`、`internal/service`:两个 PATCH 路由、DTO、Mapper、版本冲突映射与图片 URL 解析;
|
- `ids-admin-api/internal/handler`、`internal/service`:两个 PATCH 路由、DTO、Mapper、版本冲突映射与图片 URL 解析;
|
||||||
|
|||||||
441
docs/admin-freight-template.md
Normal file
441
docs/admin-freight-template.md
Normal file
@ -0,0 +1,441 @@
|
|||||||
|
# 管理端运费模板(快递发货)
|
||||||
|
|
||||||
|
**Status:** Backend rules validation **Implemented**;admin-web / 小程序 UI **未做**(另排期)。
|
||||||
|
**Scope(已落地后端):** 本服务对 `pricing_mode=2` 的 `rules_json` 做 schema + 区域存在性 + 父子 overlap 校验;区域索引来自嵌入的 [`internal/freight/region.json`](../internal/freight/region.json)。
|
||||||
|
**Scope(文档约定、UI 未实现):** `ids-admin-web` 列表 / 创建 / 编辑 / 删除;小程序结算。
|
||||||
|
**数据落点:** 表 `product.freight_templates` + Admin API(`/admin/v1/freight-templates`)→ Product gRPC。
|
||||||
|
**Depends on:** [admin-product-create-edit-phase1.md](../../ids-admin-api/docs/admin-product-create-edit-phase1.md) §2 运费模板 HTTP。
|
||||||
|
|
||||||
|
**归属判断:** 运费模板是商品销售配置主数据,且商品只持有 `freight_template_id` 引用;因此模板 CRUD、店铺作用域、启停、删除引用检查、`rules_json` schema 校验归 Product 是合适的。Fulfillment / Quote / Checkout 后续只消费已校验规则并执行计价,不作为模板主数据源。
|
||||||
|
|
||||||
|
**非目标(本期):**
|
||||||
|
|
||||||
|
- **上门自提**(页签见 §2.3:展示且 disabled,不做配置与存贮)
|
||||||
|
- 下单 / Quote 按模板实时计价(BFF 现网仍可能返回 `FREIGHT_TEMPLATE_UNSUPPORTED`;计价公式见 §3.3,供后续实现)
|
||||||
|
- admin-web / 小程序页面
|
||||||
|
- 微信物流助手、电子面单
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 结论(先读)
|
||||||
|
|
||||||
|
| # | 结论 |
|
||||||
|
| --- | --- |
|
||||||
|
| 1 | **后端 CRUD 已就绪**;缺口在 admin-web:无列表页、无创建/编辑表单、商品侧只能手输模板 ID。 |
|
||||||
|
| 2 | **UI 对齐附图「快递发货」:** 模板名称、计费方式(按件 / 按重)、配送区域表(首件/首重、运费、续件/续重、续费)、「指定可配送区域和运费」;空表初始态见表头 +「没有更多数据了」。 |
|
||||||
|
| 3 | **创建/更新一律走 `pricing_mode = 2`**,规则写入 `rules_json`(见 §3);`pricing_mode = 1`(统一运费)本期管理端不提供新建入口。 |
|
||||||
|
| 4 | **区域数据:** 源文件 [`internal/freight/region.json`](../internal/freight/region.json)(`go:embed` 校验用);admin-web 开发/构建时复制到 `src/assets/region.json`;不做区域后台接口。 |
|
||||||
|
| 5 | **上门自提本期不做**;为对齐附图,页签**显示且 disabled**,标注「即将支持」。 |
|
||||||
|
| 6 | **本服务已校验 `rules_json`(create/update)**:version/delivery/charge_type、至少一行规则、`region_codes` 字符串且落在 region.json、行内/行间父子 overlap、按件整数/按重≤3 位小数、`region_paths` 必填等长。Admin API 透传 `InvalidArgument`。 |
|
||||||
|
|
||||||
|
```text
|
||||||
|
列表 → 新建/编辑页(快递)→ 选区(region.json) + 填首续费
|
||||||
|
→ 前端完整校验(含 overlap)→ POST/PATCH { pricing_mode:2, rules_json }
|
||||||
|
商品编辑 → remote 搜索模板 + 已绑 ID 详情补回显
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 问题与目标
|
||||||
|
|
||||||
|
### 1.1 现状
|
||||||
|
|
||||||
|
| 层 | 状态 |
|
||||||
|
| --- | --- |
|
||||||
|
| Product gRPC + DB `product.freight_templates` | Implemented |
|
||||||
|
| Admin API 五接口(list/create/get/patch/delete) | Implemented;透传 Product 对 `rules_json` 的结构 / 区域 / overlap 校验错误 |
|
||||||
|
| admin-web 模板管理页 | **缺失** |
|
||||||
|
| admin-web 商品绑定 | 手输 / `allow-create` ID;注释仍写「暂无列表接口」 |
|
||||||
|
| `region.json` | [`internal/freight/region.json`](../internal/freight/region.json)(结构见 §4.2) |
|
||||||
|
| 结算按模板算运费 | 非本期;公式预约定于 §3.3 |
|
||||||
|
|
||||||
|
### 1.2 目标
|
||||||
|
|
||||||
|
1. 管理端可完整维护快递运费模板(CRUD)。
|
||||||
|
2. 创建/编辑交互对齐附图(快递可用;自提 tab disabled)。
|
||||||
|
3. 配送区域从 `region.json` 多选;**exact code 与父子层级均不可重叠**。
|
||||||
|
4. 商品编辑在「运费模板」模式下 remote 搜索本店启用模板,并可靠回显已绑 ID。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 管理端信息架构
|
||||||
|
|
||||||
|
### 2.1 路由与菜单
|
||||||
|
|
||||||
|
建议挂在商品相关导航下(与供应商/品牌同级或「物流设置」分组):
|
||||||
|
|
||||||
|
| 路由 | 页面 |
|
||||||
|
| --- | --- |
|
||||||
|
| `/product/freight-template` | 列表 |
|
||||||
|
| `/product/freight-template/create` | 创建 |
|
||||||
|
| `/product/freight-template/edit/:id` | 编辑 |
|
||||||
|
|
||||||
|
(实现时可改为 dialog 模式;**推荐独立页**以便区域选择器占宽。)
|
||||||
|
|
||||||
|
### 2.2 列表页
|
||||||
|
|
||||||
|
参考 [`supplier.vue`](../../ids-admin-web/src/views/catalog/supplier.vue) 主数据页:
|
||||||
|
|
||||||
|
| 列 | 来源 |
|
||||||
|
| --- | --- |
|
||||||
|
| 模板名称 | `name` |
|
||||||
|
| 计费方式 | 见下表「计费方式展示」 |
|
||||||
|
| 配送区域数 | `pricing_mode=2` 且规则合法时:`rules_json.rules.length`;否则 `—` |
|
||||||
|
| 状态 | `status`:1 启用 / 0 停用 |
|
||||||
|
| 更新时间 | `updated_at` |
|
||||||
|
| 操作 | 编辑、启用/停用、删除 |
|
||||||
|
|
||||||
|
**计费方式展示(必须区分历史数据):**
|
||||||
|
|
||||||
|
| 条件 | 展示文案 |
|
||||||
|
| --- | --- |
|
||||||
|
| `pricing_mode === 1` | 统一运费 |
|
||||||
|
| `pricing_mode === 2` 且 `rules_json.charge_type === 'piece'` | 按件数 |
|
||||||
|
| `pricing_mode === 2` 且 `rules_json.charge_type === 'weight'` | 按重量 |
|
||||||
|
| `pricing_mode === 2` 但 JSON 无法解析 / 缺 `charge_type` | 规则异常 |
|
||||||
|
|
||||||
|
筛选:`keyword`、`status`;分页:`page` / `page_size`。
|
||||||
|
|
||||||
|
删除:带 `expected_version`;若商品仍引用 → 展示后端 `409` 文案。
|
||||||
|
|
||||||
|
### 2.3 创建 / 编辑页(快递)
|
||||||
|
|
||||||
|
对齐附图,字段如下:
|
||||||
|
|
||||||
|
| UI | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| 页签「快递发货」 | 本期唯一可用(active) |
|
||||||
|
| 页签「上门自提」 | **显示且 `disabled`**,旁注「即将支持」;无表单、无提交字段 |
|
||||||
|
| 模板名称 * | 必填,≤64 字(与服务端一致) |
|
||||||
|
| 计费方式 | 单选:按件数 / 按重量;切换时表格列标题联动(首件↔首重、续件↔续重),单位:个 / kg |
|
||||||
|
| 配送区域表 | 初始:**表头已展示、无数据行**,空态文案 **「没有更多数据了」**(与附图一致)。有数据后:可配送区域、首(件/重)、运费(元)、续(件/重)、续费(元);支持行内编辑与删除行 |
|
||||||
|
| 「指定可配送区域和运费」 | 打开区域选择弹层 → 确认后追加一行(默认首单元=1、续单元=1;运费/续费默认 0,保存前须用户确认) |
|
||||||
|
| 保存 / 取消 | 见 §2.5 |
|
||||||
|
|
||||||
|
历史 `pricing_mode=1` 打开编辑:允许改名称/状态;规则区提示「当前为统一运费,保存区域规则将切换为 `pricing_mode=2`」;用户补齐至少一行规则后保存即转 mode=2。
|
||||||
|
|
||||||
|
### 2.4 提交校验(后端已落地;前端仍应预校验)
|
||||||
|
|
||||||
|
**本服务(权威):** `CreateFreightTemplate` / `UpdateFreightTemplate` 在 `pricing_mode=2` 或写入 `rules_json` 时调用 `freight.ValidateRulesJSON`;不合法 → gRPC `InvalidArgument` → Admin API 4xx。
|
||||||
|
**Update:** 若将 `pricing_mode` 设为 `2`,同请求必须带合法 `rules_json`。仅改名称/状态且不碰 mode/rules 时不重验旧数据。
|
||||||
|
**前端(UI 落地后):** 提交前仍做同等预校验以改善体验;不能替代后端。
|
||||||
|
|
||||||
|
后端校验清单:
|
||||||
|
|
||||||
|
- 至少一条配送规则;`version=1`,`delivery=express`,`charge_type` ∈ {piece,weight};
|
||||||
|
- 每行 `region_codes` 非空字符串,且均存在于嵌入的 `region.json`;与 `region_names` / `region_paths` 等长(**新写入 paths 必填**);
|
||||||
|
- `first_fee` / `additional_fee` ≥ 0(分);
|
||||||
|
- `charge_type=piece`:`first_unit` / `additional_unit` 为正整数;
|
||||||
|
- `charge_type=weight`:单位 > 0 且最多 3 位小数(见 §3.3);
|
||||||
|
- **区域重叠:** 同行与跨行,相同 code 或祖先–后代关系均拒绝(见 §4.4)。
|
||||||
|
|
||||||
|
### 2.5 保存交互
|
||||||
|
|
||||||
|
- 保存按钮:`loading` 期间禁用;防重复提交(单飞)。
|
||||||
|
- 成功:提示后回列表(或停留编辑并刷新 `version`)。
|
||||||
|
- `409` / 版本冲突:提示「数据已被他人更新」,**重新 `GET` 详情**后保留用户可对比;不静默覆盖。
|
||||||
|
- 删除在用 `409`:展示服务端文案,不移除行。
|
||||||
|
- 取消:有未保存变更时二次确认。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. `rules_json` 契约(前端写入 / 后端存取)
|
||||||
|
|
||||||
|
服务端对 `rules_json` **校验结构后存贮、暂不解析计价**;写入必须符合本节契约,供后续 Quote 使用。计价语义见 §3.3。
|
||||||
|
|
||||||
|
### 3.1 Schema
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "piece",
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"region_codes": ["440000", "310000"],
|
||||||
|
"region_names": ["广东省", "上海市"],
|
||||||
|
"region_paths": ["广东省", "上海市"],
|
||||||
|
"first_unit": 1,
|
||||||
|
"first_fee": 800,
|
||||||
|
"additional_unit": 1,
|
||||||
|
"additional_fee": 200
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `version` | int | 固定 `1` |
|
||||||
|
| `delivery` | string | 固定 `"express"`(自提将来另约定,本期不写) |
|
||||||
|
| `charge_type` | string | `"piece"` \| `"weight"` |
|
||||||
|
| `rules[].region_codes` | string[] | 归一化后的区域 code;**必须**为字符串(源文件 `regionId` 为 number,写入时 `String(regionId)`,如 `"210000"`)。禁止在 `rules_json` 中存 number,以免 overlap / 回填出现 `"210000" !== 210000` |
|
||||||
|
| `rules[].region_names` | string[] | 节点 `name`,与 codes 等长(短展示) |
|
||||||
|
| `rules[].region_paths` | string[] | **新写入必须写**;仅历史数据可缺失,编辑时按 code 回查 `region.json` 补全。路径为省/市/区名称以 `/` 连接(不含 `part` 分组名),如 `"辽宁省/沈阳市/和平区"`;与 codes 等长。表格优先展示 path |
|
||||||
|
| `rules[].first_unit` | number | 首件(整数)或首重(kg,见 §3.3) |
|
||||||
|
| `rules[].first_fee` | int64 | 分 |
|
||||||
|
| `rules[].additional_unit` | number | 续件(整数)或续重(kg,见 §3.3) |
|
||||||
|
| `rules[].additional_fee` | int64 | 分 |
|
||||||
|
|
||||||
|
创建/更新请求示例:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /admin/v1/freight-templates
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"name": "华东快递",
|
||||||
|
"pricing_mode": 2,
|
||||||
|
"rules_json": { "...见上..." },
|
||||||
|
"status": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
编辑还需 `expected_version`。`default_fee` 在 mode=2 时可不传。
|
||||||
|
|
||||||
|
若历史数据无 `region_paths`:编辑页用 `region_codes` 反查 `region.json` 补全 path;补全失败则回退 `region_names`。
|
||||||
|
|
||||||
|
### 3.2 与现网 `pricing_mode` 映射
|
||||||
|
|
||||||
|
| 管理端场景 | `pricing_mode` | `default_fee` | `rules_json` |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 本期创建/编辑(附图) | `2` | 省略 | 必填,§3.1 |
|
||||||
|
| 历史 mode=1 统一运费 | 保持 1 直至用户保存区域规则 | 列表可展示 `default_fee` | 编辑见 §2.3 |
|
||||||
|
|
||||||
|
### 3.3 计费语义(按件 / 按重,供 UI 与未来 Quote)
|
||||||
|
|
||||||
|
**按件数(`charge_type=piece`)**
|
||||||
|
|
||||||
|
- `first_unit` / `additional_unit`:正整数;UI 步长 1。
|
||||||
|
- 件数 `n`(正整数)运费:
|
||||||
|
|
||||||
|
```text
|
||||||
|
if n <= first_unit:
|
||||||
|
fee = first_fee
|
||||||
|
else:
|
||||||
|
extra = ceil( (n - first_unit) / additional_unit )
|
||||||
|
fee = first_fee + extra * additional_fee
|
||||||
|
```
|
||||||
|
|
||||||
|
**按重量(`charge_type=weight`)**
|
||||||
|
|
||||||
|
- 单位:**kg**。
|
||||||
|
- `first_unit` / `additional_unit`:存 number,**最多 3 位小数**;UI `precision=3`,步长 `0.001`;须 `> 0`。
|
||||||
|
- 商品合计重量 `w`(kg,计算侧同样按 3 位小数处理)运费:
|
||||||
|
|
||||||
|
```text
|
||||||
|
if w <= first_unit:
|
||||||
|
fee = first_fee
|
||||||
|
else:
|
||||||
|
extra = ceil( (w - first_unit) / additional_unit ) // 向上取整续重段数
|
||||||
|
fee = first_fee + extra * additional_fee
|
||||||
|
```
|
||||||
|
|
||||||
|
- **边界:** `w == first_unit` 只收首重费;超出部分按续重段 `ceil` 计,不足一段按一段计。
|
||||||
|
- 管理端输入超 3 位小数:提交前四舍五入到 3 位(或直接限制输入)。
|
||||||
|
|
||||||
|
本期 Quote **不实现**上述公式,但 `rules_json` 必须按此语义可解释,避免日后无法计价。
|
||||||
|
|
||||||
|
### 3.4 金额元 ↔ 分
|
||||||
|
|
||||||
|
- UI 展示/输入:元,`precision=2`。
|
||||||
|
- 提交:`fee_fen = Math.round(yuan * 100)`;回填:`yuan = fen / 100`。
|
||||||
|
- 拒绝 NaN / 负数。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. `region.json`
|
||||||
|
|
||||||
|
### 4.1 落盘位置
|
||||||
|
|
||||||
|
**Source of truth:**
|
||||||
|
|
||||||
|
```text
|
||||||
|
ids-svc-product/internal/freight/region.json
|
||||||
|
```
|
||||||
|
|
||||||
|
(与 `go:embed` 校验同源;改此文件即可。)
|
||||||
|
|
||||||
|
admin-web 读取方式(约定优先 A):
|
||||||
|
|
||||||
|
| 方式 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| A(推荐) | 开发/构建时从上述源文件 **复制**到 `ids-admin-web/src/assets/region.json`,再 `import` |
|
||||||
|
| B | Vite alias 指向 `../../ids-svc-product/internal/freight/region.json`;若需包外访问,配置 `server.fs.allow` |
|
||||||
|
|
||||||
|
选择器**只读该静态文件**,不请求后端。admin-web 副本勿手改;改源文件后重新同步。
|
||||||
|
|
||||||
|
### 4.2 源文件结构(实际)
|
||||||
|
|
||||||
|
顶层为接口包装,不是树数组:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 0,
|
||||||
|
"msg": "",
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"index": 0,
|
||||||
|
"part": "东北",
|
||||||
|
"provinces": [
|
||||||
|
{
|
||||||
|
"regionId": 210000,
|
||||||
|
"name": "辽宁省",
|
||||||
|
"cities": [
|
||||||
|
{
|
||||||
|
"regionId": 210100,
|
||||||
|
"name": "沈阳市",
|
||||||
|
"counties": [
|
||||||
|
{ "regionId": 210102, "name": "和平区" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 源字段 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `code` / `msg` | 包装字段;`code !== 0` 时前端应视为加载失败 |
|
||||||
|
| `data[]` | 按拼音/地区的**分组**列表 |
|
||||||
|
| `data[].part` | 分组名(如「东北」);**仅 UI 分组展示,不写入** `region_codes` / `region_paths` |
|
||||||
|
| `data[].index` | 分组索引;类型以源文件为准,可选用于侧栏锚点 |
|
||||||
|
| `provinces[]` | 省;字段 `regionId`(number)、`name`、`cities` |
|
||||||
|
| `cities[]` | 市;字段 `regionId`、`name`、`counties` |
|
||||||
|
| `counties[]` | 区/县;字段 `regionId`、`name` |
|
||||||
|
|
||||||
|
### 4.3 归一化为选择器树(实现必做)
|
||||||
|
|
||||||
|
内部统一树节点:`{ code: string, name: string, children?: Node[] }`。
|
||||||
|
|
||||||
|
转换规则:
|
||||||
|
|
||||||
|
```text
|
||||||
|
load region.json
|
||||||
|
assert wrapper.code === 0
|
||||||
|
for each group in data:
|
||||||
|
// part 可作为 el-tree / 侧栏分组标签,不是可选区节点
|
||||||
|
for each province in group.provinces:
|
||||||
|
node = {
|
||||||
|
code: String(province.regionId), // number → string,必须
|
||||||
|
name: province.name,
|
||||||
|
children: (province.cities || []).map(city => ({
|
||||||
|
code: String(city.regionId),
|
||||||
|
name: city.name,
|
||||||
|
children: (city.counties || []).map(county => ({
|
||||||
|
code: String(county.regionId),
|
||||||
|
name: county.name
|
||||||
|
}))
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 源 | 目标 |
|
||||||
|
| --- | --- |
|
||||||
|
| `regionId` (number) | `code` = `String(regionId)` |
|
||||||
|
| `name` | `name` |
|
||||||
|
| `provinces` / `cities` / `counties` | 层层变为 `children` |
|
||||||
|
| `part` / `index` | 保留为分组元数据;**不是**树节点,不参与 overlap |
|
||||||
|
|
||||||
|
`region_paths` 生成:自省至当前节点的 `name` 用 `/` 连接(**不含** `part`),例如选中和平区 → `"辽宁省/沈阳市/和平区"`;仅选省 → `"辽宁省"`。
|
||||||
|
|
||||||
|
### 4.4 选择器与区域重叠规则
|
||||||
|
|
||||||
|
- 弹层多选树;可选省 / 市 / 区(按产品默认勾选省级,允许下钻)。
|
||||||
|
- **冲突定义(禁用 + 保存校验同一套):**
|
||||||
|
对已占用集合 `Occupied`(其它规则行已选 code,编辑当前行时不含本行旧值或按「确认后整行替换」处理):
|
||||||
|
候选节点 `C` 与任一 `O ∈ Occupied` 冲突,当且仅当:
|
||||||
|
- `C.code === O.code`,或
|
||||||
|
- `C` 是 `O` 的祖先,或
|
||||||
|
- `C` 是 `O` 的后代。
|
||||||
|
例:已选「广东省」则不可再选「深圳市」;已选「深圳市」则不可再选「广东省」。
|
||||||
|
- 同行内多选节点之间同样做 overlap 检查(禁止同时勾选父子)。
|
||||||
|
- 确认后写入当前行(或新建行)的 `region_codes` / `region_names` / `region_paths`。
|
||||||
|
- 表格「可配送区域」列:优先 `region_paths` 顿号拼接;过长省略 + tooltip。
|
||||||
|
|
||||||
|
实现提示:加载 `region.json` 时建 `code → parentCode` 与 `code → path` 索引,overlap 用祖先链集合相交判断。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Admin API 用法(已实现,前端对接)
|
||||||
|
|
||||||
|
| 方法 | 路径 | 用途 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `GET` | `/admin/v1/freight-templates` | 列表:`page` `page_size` `keyword` `status` |
|
||||||
|
| `POST` | `/admin/v1/freight-templates` | 创建 → `201 { template }` |
|
||||||
|
| `GET` | `/admin/v1/freight-templates/{id}` | 编辑回填;商品侧补回显 |
|
||||||
|
| `PATCH` | `/admin/v1/freight-templates/{id}` | 更新(含 `expected_version`) |
|
||||||
|
| `DELETE` | `/admin/v1/freight-templates/{id}?expected_version=` | 软删;在用 → `409` |
|
||||||
|
|
||||||
|
前端模块建议:`ids-admin-web/src/api/freightTemplate.js`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 商品编辑联动
|
||||||
|
|
||||||
|
[`product/edit.vue`](../../ids-admin-web/src/views/product/edit.vue) 在 `freight_charge_type === 2` 时:
|
||||||
|
|
||||||
|
1. **`el-select` remote 搜索**:`GET /admin/v1/freight-templates?status=1&keyword=&page=1&page_size=100`;默认打开时加载前 100 条;输入关键词走 `keyword`,**不**一次性拉全站。
|
||||||
|
2. 选项展示 `name`,值为 `template_id`;去掉「暂无列表接口」注释与 `allow-create` 手输依赖。
|
||||||
|
3. **已绑定回显:** 若当前 `freight_template_id` 不在本次 options 中,则 `GET /admin/v1/freight-templates/{id}` 补一条 option;停用/软删则 disabled + 提示更换。
|
||||||
|
4. 搜索无结果且无已绑 ID 时,显示空态,不回落手输任意 ID(避免绑到他店/无效 ID)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 实现分期
|
||||||
|
|
||||||
|
| 阶段 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| **Doc**(本文) | 契约与 UI 范围 |
|
||||||
|
| **Backend**(已做) | `internal/freight`:嵌入 region.json + `ValidateRulesJSON`;create/update 接入 |
|
||||||
|
| **P0 UI**(未做) | admin-web:region 同步 + 列表 CRUD + 创建/编辑页 + 区域选择器 |
|
||||||
|
| **P1 UI**(未做) | 商品编辑 remote 搜索绑定 |
|
||||||
|
| **P2**(另文) | Quote/Checkout 按 §3.3 计价;上门自提 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 验收
|
||||||
|
|
||||||
|
| # | 场景 | 期望 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| A | 新建按件模板,选两个省,填首续费并保存 | 列表可见;GET 回填 `rules_json` 正确(金额为分);空表初始态为表头 +「没有更多数据了」 |
|
||||||
|
| B | 编辑改名、改区域、改计费方式为按重 | PATCH 成功,version +1 |
|
||||||
|
| C | 删除未被引用模板 | `204`,列表消失 |
|
||||||
|
| D | 删除仍被商品引用的模板 | `409`,前端提示 |
|
||||||
|
| E | 商品 remote 搜索选模板;已绑不在首页时详情补回显 | `freight_template_id` 正确 |
|
||||||
|
| F | 上门自提 tab | 可见、disabled、「即将支持」;无配置 |
|
||||||
|
| G | 一行选「广东省」,另一行选「深圳市」 | 选择器禁用或保存拦截,提示区域重叠 |
|
||||||
|
| H | 运费输入 `1.005` 元 | 提交为 `101` 分(`round`);回填展示一致 |
|
||||||
|
| I | 历史 `pricing_mode=1` | 列表显示「统一运费」;不误显示「规则异常/按件」 |
|
||||||
|
| J | 按重:首重 `1`、续重 `0.5`,模拟重量 `1.1` | 规则可按 §3.3 解释为 `ceil(0.1/0.5)=1` 段续费(本期可不跑 Quote,单测/文档样例即可) |
|
||||||
|
| K | 版本冲突保存 | `409` 提示并重新拉取详情 |
|
||||||
|
| L | 选辽宁省等区域并保存 | `region_codes` 为字符串(如 `"210000"`)且含 `region_paths`;GET 回填与树勾选匹配 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 风险
|
||||||
|
|
||||||
|
| 风险 | 处理 |
|
||||||
|
| --- | --- |
|
||||||
|
| `region.json` 体积大 | 异步 chunk;选择器虚拟滚动(若卡顿再做) |
|
||||||
|
| 仅 exact code 去重漏父子重叠 | §4.4 强制祖先/后代冲突 |
|
||||||
|
| admin-web 区域副本过期 | 改 `internal/freight/region.json` 后同步复制到 admin-web assets |
|
||||||
|
| 元↔分 / kg 小数 | §3.3 / §3.4 定死 |
|
||||||
|
| 历史 mode=1 | 列表文案区分;编辑引导转 mode=2 |
|
||||||
|
| 结算仍不认模板 | 产品可知晓;不在本期验收 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 索引
|
||||||
|
|
||||||
|
| 项 | 路径 |
|
||||||
|
| --- | --- |
|
||||||
|
| Admin HTTP 文档 | `ids-admin-api/docs/admin-product-create-edit-phase1.md` §2 |
|
||||||
|
| Handler | `ids-admin-api/internal/handler/freight_templates.go` |
|
||||||
|
| Product 服务 | `ids-svc-product/internal/server/freight_template_server.go` |
|
||||||
|
| 商品编辑(待改) | `ids-admin-web/src/views/product/edit.vue` |
|
||||||
|
| 区域数据(源 / embed) | `ids-svc-product/internal/freight/region.json` |
|
||||||
|
| 校验实现 | `ids-svc-product/internal/freight/rules_json.go` |
|
||||||
@ -44,7 +44,6 @@ func LoadConfig() (*Config, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Config{
|
return &Config{
|
||||||
ServerPort: getEnv("SERVER_PORT", defaultServerPort),
|
ServerPort: getEnv("SERVER_PORT", defaultServerPort),
|
||||||
PostgresDSN: dsn,
|
PostgresDSN: dsn,
|
||||||
|
|||||||
15864
internal/freight/region.json
Normal file
15864
internal/freight/region.json
Normal file
File diff suppressed because it is too large
Load Diff
120
internal/freight/region_index.go
Normal file
120
internal/freight/region_index.go
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
package freight
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "embed"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed region.json
|
||||||
|
var regionJSON []byte
|
||||||
|
|
||||||
|
// RegionIndex indexes adcodes from region.json for existence + ancestor overlap checks.
|
||||||
|
type RegionIndex struct {
|
||||||
|
parent map[string]string
|
||||||
|
known map[string]struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type regionFile struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Data []struct {
|
||||||
|
Provinces []struct {
|
||||||
|
RegionID int64 `json:"regionId"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Cities []struct {
|
||||||
|
RegionID int64 `json:"regionId"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Counties []struct {
|
||||||
|
RegionID int64 `json:"regionId"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
} `json:"counties"`
|
||||||
|
} `json:"cities"`
|
||||||
|
} `json:"provinces"`
|
||||||
|
} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
regionOnce sync.Once
|
||||||
|
regionIdx *RegionIndex
|
||||||
|
regionErr error
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultRegionIndex returns the process-wide index built from embedded region.json.
|
||||||
|
func DefaultRegionIndex() (*RegionIndex, error) {
|
||||||
|
regionOnce.Do(func() {
|
||||||
|
regionIdx, regionErr = buildRegionIndex(regionJSON)
|
||||||
|
})
|
||||||
|
return regionIdx, regionErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildRegionIndex(raw []byte) (*RegionIndex, error) {
|
||||||
|
var file regionFile
|
||||||
|
if err := json.Unmarshal(raw, &file); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse region.json: %w", err)
|
||||||
|
}
|
||||||
|
if file.Code != 0 {
|
||||||
|
return nil, fmt.Errorf("region.json code is %d, want 0", file.Code)
|
||||||
|
}
|
||||||
|
idx := &RegionIndex{
|
||||||
|
parent: make(map[string]string),
|
||||||
|
known: make(map[string]struct{}),
|
||||||
|
}
|
||||||
|
for _, group := range file.Data {
|
||||||
|
for _, province := range group.Provinces {
|
||||||
|
pCode := fmt.Sprint(province.RegionID)
|
||||||
|
idx.known[pCode] = struct{}{}
|
||||||
|
for _, city := range province.Cities {
|
||||||
|
cCode := fmt.Sprint(city.RegionID)
|
||||||
|
idx.known[cCode] = struct{}{}
|
||||||
|
idx.parent[cCode] = pCode
|
||||||
|
for _, county := range city.Counties {
|
||||||
|
dCode := fmt.Sprint(county.RegionID)
|
||||||
|
idx.known[dCode] = struct{}{}
|
||||||
|
idx.parent[dCode] = cCode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(idx.known) == 0 {
|
||||||
|
return nil, fmt.Errorf("region.json has no regions")
|
||||||
|
}
|
||||||
|
return idx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Known reports whether code exists in region.json.
|
||||||
|
func (idx *RegionIndex) Known(code string) bool {
|
||||||
|
if idx == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, ok := idx.known[code]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overlap reports same code or ancestor–descendant relationship.
|
||||||
|
func (idx *RegionIndex) Overlap(a, b string) bool {
|
||||||
|
if a == b {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if idx == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if idx.isAncestor(a, b) || idx.isAncestor(b, a) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idx *RegionIndex) isAncestor(ancestor, descendant string) bool {
|
||||||
|
cur := descendant
|
||||||
|
for {
|
||||||
|
parent, ok := idx.parent[cur]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if parent == ancestor {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
cur = parent
|
||||||
|
}
|
||||||
|
}
|
||||||
156
internal/freight/rules_json.go
Normal file
156
internal/freight/rules_json.go
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
package freight
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RulesDocument is the version-1 express freight rules_json contract.
|
||||||
|
type RulesDocument struct {
|
||||||
|
Version int `json:"version"`
|
||||||
|
Delivery string `json:"delivery"`
|
||||||
|
ChargeType string `json:"charge_type"`
|
||||||
|
Rules []RuleRow `json:"rules"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// RuleRow is one deliverable-area pricing row.
|
||||||
|
type RuleRow struct {
|
||||||
|
RegionCodes []string `json:"region_codes"`
|
||||||
|
RegionNames []string `json:"region_names"`
|
||||||
|
RegionPaths []string `json:"region_paths"`
|
||||||
|
FirstUnit float64 `json:"first_unit"`
|
||||||
|
FirstFee int64 `json:"first_fee"`
|
||||||
|
AdditionalUnit float64 `json:"additional_unit"`
|
||||||
|
AdditionalFee int64 `json:"additional_fee"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateRulesJSON validates mode=2 rules_json bytes against docs/admin-freight-template.md.
|
||||||
|
// region_paths is required (new writes). Codes must be strings present in region.json; overlap includes parent/child.
|
||||||
|
func ValidateRulesJSON(raw []byte) error {
|
||||||
|
idx, err := DefaultRegionIndex()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("region index unavailable: %w", err)
|
||||||
|
}
|
||||||
|
return ValidateRulesJSONWithIndex(raw, idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateRulesJSONWithIndex is the testable core of ValidateRulesJSON.
|
||||||
|
func ValidateRulesJSONWithIndex(raw []byte, idx *RegionIndex) error {
|
||||||
|
if len(strings.TrimSpace(string(raw))) == 0 {
|
||||||
|
return fmt.Errorf("rules_json is required")
|
||||||
|
}
|
||||||
|
var doc RulesDocument
|
||||||
|
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(&doc); err != nil {
|
||||||
|
return fmt.Errorf("rules_json invalid: %w", err)
|
||||||
|
}
|
||||||
|
if doc.Version != 1 {
|
||||||
|
return fmt.Errorf("rules_json.version must be 1")
|
||||||
|
}
|
||||||
|
if doc.Delivery != "express" {
|
||||||
|
return fmt.Errorf("rules_json.delivery must be \"express\"")
|
||||||
|
}
|
||||||
|
if doc.ChargeType != "piece" && doc.ChargeType != "weight" {
|
||||||
|
return fmt.Errorf("rules_json.charge_type must be \"piece\" or \"weight\"")
|
||||||
|
}
|
||||||
|
if len(doc.Rules) == 0 {
|
||||||
|
return fmt.Errorf("rules_json.rules must contain at least one rule")
|
||||||
|
}
|
||||||
|
|
||||||
|
occupied := make([]string, 0)
|
||||||
|
for i, rule := range doc.Rules {
|
||||||
|
prefix := fmt.Sprintf("rules_json.rules[%d]", i)
|
||||||
|
if err := validateRuleRow(prefix, doc.ChargeType, rule, idx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, code := range rule.RegionCodes {
|
||||||
|
for _, prev := range occupied {
|
||||||
|
if idx.Overlap(code, prev) {
|
||||||
|
return fmt.Errorf("%s: region %s overlaps occupied region %s", prefix, code, prev)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
occupied = append(occupied, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateRuleRow(prefix, chargeType string, rule RuleRow, idx *RegionIndex) error {
|
||||||
|
if len(rule.RegionCodes) == 0 {
|
||||||
|
return fmt.Errorf("%s.region_codes must not be empty", prefix)
|
||||||
|
}
|
||||||
|
if len(rule.RegionNames) != len(rule.RegionCodes) {
|
||||||
|
return fmt.Errorf("%s.region_names length must match region_codes", prefix)
|
||||||
|
}
|
||||||
|
if len(rule.RegionPaths) != len(rule.RegionCodes) {
|
||||||
|
return fmt.Errorf("%s.region_paths length must match region_codes (required for new writes)", prefix)
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{}, len(rule.RegionCodes))
|
||||||
|
for j, code := range rule.RegionCodes {
|
||||||
|
code = strings.TrimSpace(code)
|
||||||
|
if code == "" {
|
||||||
|
return fmt.Errorf("%s.region_codes[%d] is empty", prefix, j)
|
||||||
|
}
|
||||||
|
if _, dup := seen[code]; dup {
|
||||||
|
return fmt.Errorf("%s.region_codes contains duplicate %s", prefix, code)
|
||||||
|
}
|
||||||
|
seen[code] = struct{}{}
|
||||||
|
if !idx.Known(code) {
|
||||||
|
return fmt.Errorf("%s.region_codes[%d]=%s is not a known region", prefix, j, code)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(rule.RegionNames[j]) == "" {
|
||||||
|
return fmt.Errorf("%s.region_names[%d] is empty", prefix, j)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(rule.RegionPaths[j]) == "" {
|
||||||
|
return fmt.Errorf("%s.region_paths[%d] is empty", prefix, j)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for a := range seen {
|
||||||
|
for b := range seen {
|
||||||
|
if a >= b {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if idx.Overlap(a, b) {
|
||||||
|
return fmt.Errorf("%s: region_codes %s and %s overlap", prefix, a, b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rule.FirstFee < 0 || rule.AdditionalFee < 0 {
|
||||||
|
return fmt.Errorf("%s fees must be >= 0 (fen)", prefix)
|
||||||
|
}
|
||||||
|
switch chargeType {
|
||||||
|
case "piece":
|
||||||
|
if !isPositiveInt(rule.FirstUnit) || !isPositiveInt(rule.AdditionalUnit) {
|
||||||
|
return fmt.Errorf("%s first_unit/additional_unit must be positive integers for piece", prefix)
|
||||||
|
}
|
||||||
|
case "weight":
|
||||||
|
if err := validateWeightUnit(prefix+".first_unit", rule.FirstUnit); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := validateWeightUnit(prefix+".additional_unit", rule.AdditionalUnit); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isPositiveInt(v float64) bool {
|
||||||
|
if v <= 0 || math.IsNaN(v) || math.IsInf(v, 0) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return v == math.Trunc(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateWeightUnit(field string, v float64) error {
|
||||||
|
if v <= 0 || math.IsNaN(v) || math.IsInf(v, 0) {
|
||||||
|
return fmt.Errorf("%s must be > 0", field)
|
||||||
|
}
|
||||||
|
scaled := v * 1000
|
||||||
|
if math.Abs(scaled-math.Round(scaled)) > 1e-6 {
|
||||||
|
return fmt.Errorf("%s allows at most 3 decimal places", field)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
158
internal/freight/rules_json_test.go
Normal file
158
internal/freight/rules_json_test.go
Normal file
@ -0,0 +1,158 @@
|
|||||||
|
package freight
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidateRulesJSON_PieceOK(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "piece",
|
||||||
|
"rules": [{
|
||||||
|
"region_codes": ["210000", "310000"],
|
||||||
|
"region_names": ["辽宁省", "上海市"],
|
||||||
|
"region_paths": ["辽宁省", "上海市"],
|
||||||
|
"first_unit": 1,
|
||||||
|
"first_fee": 800,
|
||||||
|
"additional_unit": 1,
|
||||||
|
"additional_fee": 200
|
||||||
|
}]
|
||||||
|
}`)
|
||||||
|
if err := ValidateRulesJSON(raw); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRulesJSON_WeightOK(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "weight",
|
||||||
|
"rules": [{
|
||||||
|
"region_codes": ["210000"],
|
||||||
|
"region_names": ["辽宁省"],
|
||||||
|
"region_paths": ["辽宁省"],
|
||||||
|
"first_unit": 1,
|
||||||
|
"first_fee": 800,
|
||||||
|
"additional_unit": 0.5,
|
||||||
|
"additional_fee": 200
|
||||||
|
}]
|
||||||
|
}`)
|
||||||
|
if err := ValidateRulesJSON(raw); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRulesJSON_ParentChildOverlap(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "piece",
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"region_codes": ["210000"],
|
||||||
|
"region_names": ["辽宁省"],
|
||||||
|
"region_paths": ["辽宁省"],
|
||||||
|
"first_unit": 1, "first_fee": 0, "additional_unit": 1, "additional_fee": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"region_codes": ["210100"],
|
||||||
|
"region_names": ["沈阳市"],
|
||||||
|
"region_paths": ["辽宁省/沈阳市"],
|
||||||
|
"first_unit": 1, "first_fee": 0, "additional_unit": 1, "additional_fee": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}`)
|
||||||
|
err := ValidateRulesJSON(raw)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "overlap") {
|
||||||
|
t.Fatalf("want overlap error, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRulesJSON_SameRowOverlap(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "piece",
|
||||||
|
"rules": [{
|
||||||
|
"region_codes": ["210000", "210100"],
|
||||||
|
"region_names": ["辽宁省", "沈阳市"],
|
||||||
|
"region_paths": ["辽宁省", "辽宁省/沈阳市"],
|
||||||
|
"first_unit": 1, "first_fee": 0, "additional_unit": 1, "additional_fee": 0
|
||||||
|
}]
|
||||||
|
}`)
|
||||||
|
err := ValidateRulesJSON(raw)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "overlap") {
|
||||||
|
t.Fatalf("want overlap error, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRulesJSON_RejectNumericCodes(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "piece",
|
||||||
|
"rules": [{
|
||||||
|
"region_codes": [210000],
|
||||||
|
"region_names": ["辽宁省"],
|
||||||
|
"region_paths": ["辽宁省"],
|
||||||
|
"first_unit": 1, "first_fee": 0, "additional_unit": 1, "additional_fee": 0
|
||||||
|
}]
|
||||||
|
}`)
|
||||||
|
if err := ValidateRulesJSON(raw); err == nil {
|
||||||
|
t.Fatal("expected error for numeric region_codes")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRulesJSON_RequirePaths(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "piece",
|
||||||
|
"rules": [{
|
||||||
|
"region_codes": ["210000"],
|
||||||
|
"region_names": ["辽宁省"],
|
||||||
|
"first_unit": 1, "first_fee": 0, "additional_unit": 1, "additional_fee": 0
|
||||||
|
}]
|
||||||
|
}`)
|
||||||
|
err := ValidateRulesJSON(raw)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "region_paths") {
|
||||||
|
t.Fatalf("want region_paths error, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRulesJSON_WeightPrecision(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"version": 1,
|
||||||
|
"delivery": "express",
|
||||||
|
"charge_type": "weight",
|
||||||
|
"rules": [{
|
||||||
|
"region_codes": ["210000"],
|
||||||
|
"region_names": ["辽宁省"],
|
||||||
|
"region_paths": ["辽宁省"],
|
||||||
|
"first_unit": 1.0001,
|
||||||
|
"first_fee": 0,
|
||||||
|
"additional_unit": 1,
|
||||||
|
"additional_fee": 0
|
||||||
|
}]
|
||||||
|
}`)
|
||||||
|
err := ValidateRulesJSON(raw)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "3 decimal") {
|
||||||
|
t.Fatalf("want precision error, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegionIndex_Known(t *testing.T) {
|
||||||
|
idx, err := DefaultRegionIndex()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !idx.Known("210000") || !idx.Known("210102") {
|
||||||
|
t.Fatal("expected Liaoning / Heping to be known")
|
||||||
|
}
|
||||||
|
if idx.Known("999999") {
|
||||||
|
t.Fatal("unknown code should not be known")
|
||||||
|
}
|
||||||
|
}
|
||||||
37
internal/postgresutc/open.go
Normal file
37
internal/postgresutc/open.go
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
package postgresutc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/stdlib"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Open returns a *sql.DB that forces TIME ZONE UTC on every physical connection.
|
||||||
|
// RuntimeParams and AfterConnect both set UTC; callers must not rely on POSTGRES_TIME_ZONE.
|
||||||
|
func Open(dsn string) (*sql.DB, error) {
|
||||||
|
cfg, err := parseConfig(dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
db := stdlib.OpenDB(*cfg, stdlib.OptionAfterConnect(func(ctx context.Context, conn *pgx.Conn) error {
|
||||||
|
_, err := conn.Exec(ctx, "SET TIME ZONE 'UTC'")
|
||||||
|
return err
|
||||||
|
}))
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseConfig(dsn string) (*pgx.ConnConfig, error) {
|
||||||
|
cfg, err := pgx.ParseConfig(dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse postgres dsn: %w", err)
|
||||||
|
}
|
||||||
|
if cfg.RuntimeParams == nil {
|
||||||
|
cfg.RuntimeParams = make(map[string]string)
|
||||||
|
}
|
||||||
|
cfg.RuntimeParams["timezone"] = "UTC"
|
||||||
|
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
562
internal/repository/catalog_master_repository.go
Normal file
562
internal/repository/catalog_master_repository.go
Normal file
@ -0,0 +1,562 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrSupplierNotFound = errors.New("supplier not found")
|
||||||
|
ErrBrandNotFound = errors.New("brand not found")
|
||||||
|
ErrSupplierVersionConflict = errors.New("supplier version conflict")
|
||||||
|
ErrBrandVersionConflict = errors.New("brand version conflict")
|
||||||
|
ErrDuplicateSupplierCode = errors.New("supplier_code already exists")
|
||||||
|
ErrDuplicateBrandCode = errors.New("brand_code already exists")
|
||||||
|
ErrSupplierHasBrands = errors.New("supplier has non-deleted brands")
|
||||||
|
ErrSupplierHasActiveBrands = errors.New("supplier has active brands")
|
||||||
|
ErrBrandInUse = errors.New("brand is referenced by products")
|
||||||
|
ErrSupplierInactive = errors.New("supplier must be enabled")
|
||||||
|
// Keep the historical client-visible message for an inactive brand while
|
||||||
|
// retaining a distinct sentinel so the Admin API can point at brand_id.
|
||||||
|
ErrBrandInactive = errors.New("supplier must be enabled")
|
||||||
|
ErrBrandSupplierMismatch = errors.New("brand does not belong to supplier")
|
||||||
|
)
|
||||||
|
|
||||||
|
type SupplierAttachmentRecord struct {
|
||||||
|
FileID string `json:"file_id"`
|
||||||
|
FileName string `json:"file_name"`
|
||||||
|
FileType string `json:"file_type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SupplierRecord struct {
|
||||||
|
ID string
|
||||||
|
Name, Alias, SupplierCode string
|
||||||
|
Attachments []SupplierAttachmentRecord
|
||||||
|
Brands []BrandRecord
|
||||||
|
ContactName, ContactPhone, Remark string
|
||||||
|
Status, Version int32
|
||||||
|
Scope StoreScope
|
||||||
|
CreatedAt, UpdatedAt time.Time
|
||||||
|
DeletedAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type BrandRecord struct {
|
||||||
|
ID string
|
||||||
|
Name, Alias, BrandCode, SupplierID string
|
||||||
|
Status, Version int32
|
||||||
|
ProductCount int64
|
||||||
|
Scope StoreScope
|
||||||
|
CreatedAt, UpdatedAt time.Time
|
||||||
|
DeletedAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type SupplierListFilter struct {
|
||||||
|
Query string
|
||||||
|
Status *int32
|
||||||
|
Page, PageSize int32
|
||||||
|
}
|
||||||
|
type BrandListFilter struct {
|
||||||
|
Query, SupplierID string
|
||||||
|
Status *int32
|
||||||
|
Page, PageSize int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type SupplierPatch struct {
|
||||||
|
ExpectedVersion int32
|
||||||
|
Name, Alias, SupplierCode *string
|
||||||
|
Attachments *[]SupplierAttachmentRecord
|
||||||
|
ContactName, ContactPhone, Remark *string
|
||||||
|
}
|
||||||
|
type BrandPatch struct {
|
||||||
|
ExpectedVersion int32
|
||||||
|
Name, Alias, BrandCode, SupplierID *string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) CreateSupplier(ctx context.Context, supplier SupplierRecord) (*SupplierRecord, error) {
|
||||||
|
if err := requireWriteScope(supplier.Scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
attachments, err := json.Marshal(supplier.Attachments)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("marshal supplier attachments: %w", err)
|
||||||
|
}
|
||||||
|
_, err = r.db.ExecContext(ctx, `INSERT INTO product.suppliers
|
||||||
|
(id,name,alias,supplier_code,attachments,contact_name,contact_phone,remark,status,tenant_id,store_id)
|
||||||
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, supplier.ID, supplier.Name, supplier.Alias, supplier.SupplierCode, attachments, supplier.ContactName, supplier.ContactPhone, supplier.Remark, supplier.Status, supplier.Scope.TenantID, supplier.Scope.StoreID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapCatalogWriteError(err, ErrDuplicateSupplierCode)
|
||||||
|
}
|
||||||
|
return r.GetSupplier(ctx, supplier.ID, supplier.Scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) GetSupplier(ctx context.Context, id string, scope StoreScope) (*SupplierRecord, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
row := r.db.QueryRowContext(ctx, supplierSelect+` WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID)
|
||||||
|
supplier, err := scanSupplier(row)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrSupplierNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
values := []SupplierRecord{*supplier}
|
||||||
|
if err := r.populateSupplierBrands(ctx, values, "", scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &values[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) ListSuppliers(ctx context.Context, filter SupplierListFilter, scope StoreScope) ([]SupplierRecord, int64, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
where, args := catalogWhere(scope, filter.Query, filter.Status, "", false)
|
||||||
|
var total int64
|
||||||
|
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.suppliers`+where, args...).Scan(&total); err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("count suppliers: %w", err)
|
||||||
|
}
|
||||||
|
args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize)
|
||||||
|
rows, err := r.db.QueryContext(ctx, supplierSelect+where+fmt.Sprintf(" ORDER BY created_at DESC, id DESC LIMIT $%d OFFSET $%d", len(args)-1, len(args)), args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("list suppliers: %w", err)
|
||||||
|
}
|
||||||
|
out := make([]SupplierRecord, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
value, err := scanSupplier(rows)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
out = append(out, *value)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("close supplier rows: %w", err)
|
||||||
|
}
|
||||||
|
if err := r.populateSupplierBrands(ctx, out, filter.Query, scope); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
return out, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) UpdateSupplier(ctx context.Context, id string, patch SupplierPatch, scope StoreScope) (*SupplierRecord, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sets, args := []string{}, []any{}
|
||||||
|
add := func(column string, value any) {
|
||||||
|
args = append(args, value)
|
||||||
|
sets = append(sets, fmt.Sprintf("%s=$%d", column, len(args)))
|
||||||
|
}
|
||||||
|
if patch.Name != nil {
|
||||||
|
add("name", *patch.Name)
|
||||||
|
}
|
||||||
|
if patch.Alias != nil {
|
||||||
|
add("alias", *patch.Alias)
|
||||||
|
}
|
||||||
|
if patch.SupplierCode != nil {
|
||||||
|
add("supplier_code", *patch.SupplierCode)
|
||||||
|
}
|
||||||
|
if patch.Attachments != nil {
|
||||||
|
raw, err := json.Marshal(*patch.Attachments)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
add("attachments", raw)
|
||||||
|
}
|
||||||
|
if patch.ContactName != nil {
|
||||||
|
add("contact_name", *patch.ContactName)
|
||||||
|
}
|
||||||
|
if patch.ContactPhone != nil {
|
||||||
|
add("contact_phone", *patch.ContactPhone)
|
||||||
|
}
|
||||||
|
if patch.Remark != nil {
|
||||||
|
add("remark", *patch.Remark)
|
||||||
|
}
|
||||||
|
if len(sets) == 0 {
|
||||||
|
return nil, errors.New("update_mask must contain at least one mutable field")
|
||||||
|
}
|
||||||
|
sets = append(sets, "updated_at=NOW()", "version=version+1")
|
||||||
|
args = append(args, id, scope.TenantID, scope.StoreID, patch.ExpectedVersion)
|
||||||
|
query := fmt.Sprintf(`UPDATE product.suppliers SET %s WHERE id=$%d AND tenant_id=$%d AND store_id=$%d AND version=$%d AND deleted_at IS NULL`, strings.Join(sets, ","), len(args)-3, len(args)-2, len(args)-1, len(args))
|
||||||
|
result, err := r.db.ExecContext(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapCatalogWriteError(err, ErrDuplicateSupplierCode)
|
||||||
|
}
|
||||||
|
changed, _ := result.RowsAffected()
|
||||||
|
if changed == 0 {
|
||||||
|
return nil, r.supplierUpdateMiss(ctx, id, patch.ExpectedVersion, scope)
|
||||||
|
}
|
||||||
|
return r.GetSupplier(ctx, id, scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) UpdateSupplierStatus(ctx context.Context, id string, statusValue, expectedVersion int32, scope StoreScope) (*SupplierRecord, error) {
|
||||||
|
if statusValue == 0 {
|
||||||
|
var active int64
|
||||||
|
err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.brands WHERE supplier_id=$1 AND tenant_id=$2 AND store_id=$3 AND status=1 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&active)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if active > 0 {
|
||||||
|
return nil, ErrSupplierHasActiveBrands
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result, err := r.db.ExecContext(ctx, `UPDATE product.suppliers SET status=$1,updated_at=NOW(),version=version+1 WHERE id=$2 AND tenant_id=$3 AND store_id=$4 AND version=$5 AND deleted_at IS NULL`, statusValue, id, scope.TenantID, scope.StoreID, expectedVersion)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
changed, _ := result.RowsAffected()
|
||||||
|
if changed == 0 {
|
||||||
|
return nil, r.supplierUpdateMiss(ctx, id, expectedVersion, scope)
|
||||||
|
}
|
||||||
|
return r.GetSupplier(ctx, id, scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) DeleteSupplier(ctx context.Context, id string, expectedVersion int32, scope StoreScope) (*time.Time, error) {
|
||||||
|
var brands int64
|
||||||
|
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.brands WHERE supplier_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&brands); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if brands > 0 {
|
||||||
|
return nil, ErrSupplierHasBrands
|
||||||
|
}
|
||||||
|
var deleted time.Time
|
||||||
|
err := r.db.QueryRowContext(ctx, `UPDATE product.suppliers SET deleted_at=NOW(),updated_at=NOW(),version=version+1 WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND version=$4 AND deleted_at IS NULL RETURNING deleted_at`, id, scope.TenantID, scope.StoreID, expectedVersion).Scan(&deleted)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, r.supplierUpdateMiss(ctx, id, expectedVersion, scope)
|
||||||
|
}
|
||||||
|
return &deleted, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) CreateBrand(ctx context.Context, brand BrandRecord) (*BrandRecord, error) {
|
||||||
|
if err := requireWriteScope(brand.Scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.ensureEnabledSupplier(ctx, brand.SupplierID, brand.Scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, err := r.db.ExecContext(ctx, `INSERT INTO product.brands (id,name,alias,brand_code,supplier_id,status,tenant_id,store_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, brand.ID, brand.Name, brand.Alias, brand.BrandCode, brand.SupplierID, brand.Status, brand.Scope.TenantID, brand.Scope.StoreID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapCatalogWriteError(err, ErrDuplicateBrandCode)
|
||||||
|
}
|
||||||
|
return r.GetBrand(ctx, brand.ID, brand.Scope)
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) GetBrand(ctx context.Context, id string, scope StoreScope) (*BrandRecord, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
row := r.db.QueryRowContext(ctx, brandSelect+` WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID)
|
||||||
|
value, err := scanBrand(row)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrBrandNotFound
|
||||||
|
}
|
||||||
|
return value, err
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) ListBrands(ctx context.Context, filter BrandListFilter, scope StoreScope) ([]BrandRecord, int64, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
where, args := catalogWhere(scope, filter.Query, filter.Status, filter.SupplierID, true)
|
||||||
|
var total int64
|
||||||
|
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.brands`+where, args...).Scan(&total); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
args = append(args, filter.PageSize, (filter.Page-1)*filter.PageSize)
|
||||||
|
rows, err := r.db.QueryContext(ctx, brandSelect+where+fmt.Sprintf(" ORDER BY created_at DESC,id DESC LIMIT $%d OFFSET $%d", len(args)-1, len(args)), args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []BrandRecord{}
|
||||||
|
for rows.Next() {
|
||||||
|
value, err := scanBrand(rows)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
out = append(out, *value)
|
||||||
|
}
|
||||||
|
return out, total, rows.Err()
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) UpdateBrand(ctx context.Context, id string, patch BrandPatch, scope StoreScope) (*BrandRecord, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if patch.SupplierID != nil {
|
||||||
|
if err := r.ensureEnabledSupplier(ctx, *patch.SupplierID, scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sets, args := []string{}, []any{}
|
||||||
|
add := func(c string, v any) {
|
||||||
|
args = append(args, v)
|
||||||
|
sets = append(sets, fmt.Sprintf("%s=$%d", c, len(args)))
|
||||||
|
}
|
||||||
|
if patch.Name != nil {
|
||||||
|
add("name", *patch.Name)
|
||||||
|
}
|
||||||
|
if patch.Alias != nil {
|
||||||
|
add("alias", *patch.Alias)
|
||||||
|
}
|
||||||
|
if patch.BrandCode != nil {
|
||||||
|
add("brand_code", *patch.BrandCode)
|
||||||
|
}
|
||||||
|
if patch.SupplierID != nil {
|
||||||
|
add("supplier_id", *patch.SupplierID)
|
||||||
|
}
|
||||||
|
if len(sets) == 0 {
|
||||||
|
return nil, errors.New("update_mask must contain at least one mutable field")
|
||||||
|
}
|
||||||
|
sets = append(sets, "updated_at=NOW()", "version=version+1")
|
||||||
|
args = append(args, id, scope.TenantID, scope.StoreID, patch.ExpectedVersion)
|
||||||
|
query := fmt.Sprintf(`UPDATE product.brands SET %s WHERE id=$%d AND tenant_id=$%d AND store_id=$%d AND version=$%d AND deleted_at IS NULL`, strings.Join(sets, ","), len(args)-3, len(args)-2, len(args)-1, len(args))
|
||||||
|
result, err := r.db.ExecContext(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapCatalogWriteError(err, ErrDuplicateBrandCode)
|
||||||
|
}
|
||||||
|
changed, _ := result.RowsAffected()
|
||||||
|
if changed == 0 {
|
||||||
|
return nil, r.brandUpdateMiss(ctx, id, patch.ExpectedVersion, scope)
|
||||||
|
}
|
||||||
|
return r.GetBrand(ctx, id, scope)
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) UpdateBrandStatus(ctx context.Context, id string, statusValue, expectedVersion int32, scope StoreScope) (*BrandRecord, error) {
|
||||||
|
result, err := r.db.ExecContext(ctx, `UPDATE product.brands SET status=$1,updated_at=NOW(),version=version+1 WHERE id=$2 AND tenant_id=$3 AND store_id=$4 AND version=$5 AND deleted_at IS NULL`, statusValue, id, scope.TenantID, scope.StoreID, expectedVersion)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
changed, _ := result.RowsAffected()
|
||||||
|
if changed == 0 {
|
||||||
|
return nil, r.brandUpdateMiss(ctx, id, expectedVersion, scope)
|
||||||
|
}
|
||||||
|
return r.GetBrand(ctx, id, scope)
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) DeleteBrand(ctx context.Context, id string, expectedVersion int32, scope StoreScope) (*time.Time, error) {
|
||||||
|
var used int64
|
||||||
|
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.products WHERE brand_id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&used); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if used > 0 {
|
||||||
|
return nil, ErrBrandInUse
|
||||||
|
}
|
||||||
|
var deleted time.Time
|
||||||
|
err := r.db.QueryRowContext(ctx, `UPDATE product.brands SET deleted_at=NOW(),updated_at=NOW(),version=version+1 WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND version=$4 AND deleted_at IS NULL RETURNING deleted_at`, id, scope.TenantID, scope.StoreID, expectedVersion).Scan(&deleted)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, r.brandUpdateMiss(ctx, id, expectedVersion, scope)
|
||||||
|
}
|
||||||
|
return &deleted, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const supplierSelect = `SELECT id,name,alias,supplier_code,attachments,contact_name,contact_phone,remark,status,tenant_id,store_id,version,created_at,updated_at,deleted_at FROM product.suppliers`
|
||||||
|
const brandSelect = `SELECT b.id,b.name,b.alias,b.brand_code,b.supplier_id,b.status,b.tenant_id,b.store_id,b.version,b.created_at,b.updated_at,b.deleted_at,
|
||||||
|
COALESCE((SELECT COUNT(*) FROM product.products p WHERE p.brand_id=b.id AND p.tenant_id=b.tenant_id AND p.store_id=b.store_id AND p.deleted_at IS NULL), 0)
|
||||||
|
FROM product.brands b`
|
||||||
|
|
||||||
|
type scanner interface{ Scan(...any) error }
|
||||||
|
|
||||||
|
func scanSupplier(row scanner) (*SupplierRecord, error) {
|
||||||
|
var value SupplierRecord
|
||||||
|
var raw []byte
|
||||||
|
var deleted sql.NullTime
|
||||||
|
err := row.Scan(&value.ID, &value.Name, &value.Alias, &value.SupplierCode, &raw, &value.ContactName, &value.ContactPhone, &value.Remark, &value.Status, &value.Scope.TenantID, &value.Scope.StoreID, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &value.Attachments); err != nil {
|
||||||
|
return nil, fmt.Errorf("decode supplier attachments: %w", err)
|
||||||
|
}
|
||||||
|
if deleted.Valid {
|
||||||
|
value.DeletedAt = &deleted.Time
|
||||||
|
}
|
||||||
|
return &value, nil
|
||||||
|
}
|
||||||
|
func scanBrand(row scanner) (*BrandRecord, error) {
|
||||||
|
var value BrandRecord
|
||||||
|
var deleted sql.NullTime
|
||||||
|
err := row.Scan(&value.ID, &value.Name, &value.Alias, &value.BrandCode, &value.SupplierID, &value.Status, &value.Scope.TenantID, &value.Scope.StoreID, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted, &value.ProductCount)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if deleted.Valid {
|
||||||
|
value.DeletedAt = &deleted.Time
|
||||||
|
}
|
||||||
|
return &value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// populateSupplierBrands batch-loads brands for the supplied suppliers. It is
|
||||||
|
// deliberately separate from the paginated supplier query: joining brands
|
||||||
|
// before pagination would duplicate suppliers and corrupt total/page results.
|
||||||
|
// A non-empty query narrows each nested brand list to matching brand fields.
|
||||||
|
func (r *ProductRepository) populateSupplierBrands(ctx context.Context, suppliers []SupplierRecord, query string, scope StoreScope) error {
|
||||||
|
if len(suppliers) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
ids := make([]int64, 0, len(suppliers))
|
||||||
|
byID := make(map[string]*SupplierRecord, len(suppliers))
|
||||||
|
for i := range suppliers {
|
||||||
|
suppliers[i].Brands = []BrandRecord{}
|
||||||
|
id, err := parseID(suppliers[i].ID, "supplier_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ids = append(ids, id)
|
||||||
|
byID[suppliers[i].ID] = &suppliers[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
placeholders, idArgs := productIDPlaceholders(ids, 3)
|
||||||
|
args := append([]any{scope.TenantID, scope.StoreID}, idArgs...)
|
||||||
|
where := ` WHERE b.tenant_id=$1 AND b.store_id=$2 AND b.deleted_at IS NULL
|
||||||
|
AND b.supplier_id IN (` + placeholders + `)`
|
||||||
|
if keyword := strings.TrimSpace(query); keyword != "" {
|
||||||
|
args = append(args, "%"+keyword+"%")
|
||||||
|
position := len(args)
|
||||||
|
where += fmt.Sprintf(" AND (b.name ILIKE $%d OR b.alias ILIKE $%d OR b.brand_code ILIKE $%d)", position, position, position)
|
||||||
|
}
|
||||||
|
rows, err := r.db.QueryContext(ctx, `SELECT b.id,b.name,b.alias,b.brand_code,b.supplier_id,b.status,b.tenant_id,b.store_id,b.version,b.created_at,b.updated_at,b.deleted_at,
|
||||||
|
COALESCE((SELECT COUNT(*) FROM product.products p WHERE p.brand_id=b.id AND p.tenant_id=b.tenant_id AND p.store_id=b.store_id AND p.deleted_at IS NULL), 0)
|
||||||
|
FROM product.brands b`+where+` ORDER BY b.created_at DESC, b.id DESC`, args...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("list supplier brands: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
brand, err := scanBrand(rows)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("scan supplier brand: %w", err)
|
||||||
|
}
|
||||||
|
if supplier := byID[brand.SupplierID]; supplier != nil {
|
||||||
|
supplier.Brands = append(supplier.Brands, *brand)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return fmt.Errorf("iterate supplier brands: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func catalogWhere(scope StoreScope, query string, statusValue *int32, supplierID string, isBrand bool) (string, []any) {
|
||||||
|
args := []any{scope.TenantID, scope.StoreID}
|
||||||
|
where := ` WHERE tenant_id=$1 AND store_id=$2 AND deleted_at IS NULL`
|
||||||
|
if strings.TrimSpace(query) != "" {
|
||||||
|
args = append(args, "%"+strings.TrimSpace(query)+"%")
|
||||||
|
queryPosition := len(args)
|
||||||
|
if isBrand {
|
||||||
|
where += fmt.Sprintf(" AND (name ILIKE $%d OR alias ILIKE $%d OR brand_code ILIKE $%d)", queryPosition, queryPosition, queryPosition)
|
||||||
|
} else {
|
||||||
|
where += fmt.Sprintf(` AND (
|
||||||
|
name ILIKE $%d
|
||||||
|
OR alias ILIKE $%d
|
||||||
|
OR supplier_code ILIKE $%d
|
||||||
|
OR EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.brands b
|
||||||
|
WHERE b.supplier_id = product.suppliers.id
|
||||||
|
AND b.tenant_id = product.suppliers.tenant_id
|
||||||
|
AND b.store_id = product.suppliers.store_id
|
||||||
|
AND b.deleted_at IS NULL
|
||||||
|
AND (b.name ILIKE $%d OR b.alias ILIKE $%d OR b.brand_code ILIKE $%d)
|
||||||
|
)
|
||||||
|
)`, queryPosition, queryPosition, queryPosition, queryPosition, queryPosition, queryPosition)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if statusValue != nil {
|
||||||
|
args = append(args, *statusValue)
|
||||||
|
where += fmt.Sprintf(" AND status=$%d", len(args))
|
||||||
|
}
|
||||||
|
if isBrand && strings.TrimSpace(supplierID) != "" {
|
||||||
|
args = append(args, supplierID)
|
||||||
|
where += fmt.Sprintf(" AND supplier_id=$%d", len(args))
|
||||||
|
}
|
||||||
|
return where, args
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) ensureEnabledSupplier(ctx context.Context, id string, scope StoreScope) error {
|
||||||
|
var statusValue int32
|
||||||
|
err := r.db.QueryRowContext(ctx, `SELECT status FROM product.suppliers WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, id, scope.TenantID, scope.StoreID).Scan(&statusValue)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrSupplierNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if statusValue != 1 {
|
||||||
|
return ErrSupplierInactive
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateProductMasterRefs verifies that optional product supplier and brand
|
||||||
|
// references are live in the same store and that a supplied pair is related.
|
||||||
|
func (r *ProductRepository) ValidateProductMasterRefs(ctx context.Context, supplierID, brandID string, scope StoreScope) error {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if supplierID != "" {
|
||||||
|
if err := r.ensureEnabledSupplier(ctx, supplierID, scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if brandID == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var brandSupplierID string
|
||||||
|
var brandStatus int32
|
||||||
|
err := r.db.QueryRowContext(ctx, `SELECT supplier_id, status FROM product.brands WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL`, brandID, scope.TenantID, scope.StoreID).Scan(&brandSupplierID, &brandStatus)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrBrandNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if brandStatus != 1 {
|
||||||
|
return ErrBrandInactive
|
||||||
|
}
|
||||||
|
if err := r.ensureEnabledSupplier(ctx, brandSupplierID, scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if supplierID != "" && supplierID != brandSupplierID {
|
||||||
|
return ErrBrandSupplierMismatch
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) supplierUpdateMiss(ctx context.Context, id string, version int32, scope StoreScope) error {
|
||||||
|
current, err := r.GetSupplier(ctx, id, scope)
|
||||||
|
if errors.Is(err, ErrSupplierNotFound) {
|
||||||
|
return ErrSupplierNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if current.Version != version {
|
||||||
|
return ErrSupplierVersionConflict
|
||||||
|
}
|
||||||
|
return ErrSupplierNotFound
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) brandUpdateMiss(ctx context.Context, id string, version int32, scope StoreScope) error {
|
||||||
|
current, err := r.GetBrand(ctx, id, scope)
|
||||||
|
if errors.Is(err, ErrBrandNotFound) {
|
||||||
|
return ErrBrandNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if current.Version != version {
|
||||||
|
return ErrBrandVersionConflict
|
||||||
|
}
|
||||||
|
return ErrBrandNotFound
|
||||||
|
}
|
||||||
|
func mapCatalogWriteError(err error, duplicate error) error {
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||||
|
return duplicate
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
34
internal/repository/catalog_master_repository_test.go
Normal file
34
internal/repository/catalog_master_repository_test.go
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCatalogWhereSupplierQueryIncludesBrandFieldsWithoutJoin(t *testing.T) {
|
||||||
|
where, args := catalogWhere(StoreScope{TenantID: 10, StoreID: 20}, "QF", nil, "", false)
|
||||||
|
|
||||||
|
if len(args) != 3 || args[2] != "%QF%" {
|
||||||
|
t.Fatalf("catalogWhere() args = %#v, want tenant, store, keyword", args)
|
||||||
|
}
|
||||||
|
for _, fragment := range []string{
|
||||||
|
"EXISTS", "FROM product.brands b", "b.name ILIKE $3", "b.alias ILIKE $3", "b.brand_code ILIKE $3",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(where, fragment) {
|
||||||
|
t.Errorf("catalogWhere() missing %q in %s", fragment, where)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(where, "JOIN product.brands") {
|
||||||
|
t.Fatalf("catalogWhere() must use EXISTS to avoid duplicate suppliers: %s", where)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCatalogWhereBrandQueryDoesNotAddSupplierBrandExists(t *testing.T) {
|
||||||
|
where, _ := catalogWhere(StoreScope{TenantID: 10, StoreID: 20}, "QF", nil, "", true)
|
||||||
|
if strings.Contains(where, "EXISTS") {
|
||||||
|
t.Fatalf("brand list query must not add supplier-brand EXISTS predicate: %s", where)
|
||||||
|
}
|
||||||
|
if !strings.Contains(where, "brand_code ILIKE $3") {
|
||||||
|
t.Fatalf("brand list query missing brand code predicate: %s", where)
|
||||||
|
}
|
||||||
|
}
|
||||||
11
internal/repository/category_binding_test.go
Normal file
11
internal/repository/category_binding_test.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestAddProductsToCategoryRequiresStoreScope(t *testing.T) {
|
||||||
|
repository := &ProductRepository{}
|
||||||
|
err := repository.AddProductsToCategory(nil, "2001", []string{"3001"}, []string{"1001"}, StoreScope{})
|
||||||
|
if err != ErrStoreScopeRequired {
|
||||||
|
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
|
||||||
|
}
|
||||||
|
}
|
||||||
335
internal/repository/freight_template_repository.go
Normal file
335
internal/repository/freight_template_repository.go
Normal file
@ -0,0 +1,335 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrFreightTemplateNotFound = errors.New("freight template not found")
|
||||||
|
ErrFreightTemplateVersionConflict = errors.New("freight template version conflict")
|
||||||
|
ErrFreightTemplateInUse = errors.New("freight template is referenced by products")
|
||||||
|
ErrFreightTemplateNameExists = errors.New("freight template name already exists")
|
||||||
|
)
|
||||||
|
|
||||||
|
// FreightTemplateRecord is product.freight_templates.
|
||||||
|
type FreightTemplateRecord struct {
|
||||||
|
ID string
|
||||||
|
Name string
|
||||||
|
PricingMode int32
|
||||||
|
DefaultFee *int64
|
||||||
|
RulesJSON []byte
|
||||||
|
Status int32
|
||||||
|
Version int32
|
||||||
|
Scope StoreScope
|
||||||
|
CreatedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
DeletedAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// FreightTemplateListFilter pages store-scoped templates.
|
||||||
|
type FreightTemplateListFilter struct {
|
||||||
|
Keyword string
|
||||||
|
ExactMatch bool
|
||||||
|
Status *int32
|
||||||
|
Page, PageSize int32
|
||||||
|
}
|
||||||
|
|
||||||
|
// FreightTemplatePatch is an optimistic update.
|
||||||
|
type FreightTemplatePatch struct {
|
||||||
|
ExpectedVersion int32
|
||||||
|
Name *string
|
||||||
|
PricingMode *int32
|
||||||
|
DefaultFee *int64
|
||||||
|
DefaultFeeSet bool
|
||||||
|
RulesJSON *[]byte
|
||||||
|
Status *int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) ensureFreightTemplateSchema(ctx context.Context) error {
|
||||||
|
_, err := r.db.ExecContext(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS product.freight_templates (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
pricing_mode SMALLINT NOT NULL DEFAULT 1 CHECK (pricing_mode IN (1, 2)),
|
||||||
|
default_fee BIGINT CHECK (default_fee IS NULL OR default_fee >= 0),
|
||||||
|
rules_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_freight_templates_store
|
||||||
|
ON product.freight_templates (store_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_freight_templates_store_normalized_name_active
|
||||||
|
ON product.freight_templates (store_id, LOWER(BTRIM(name))) WHERE deleted_at IS NULL;
|
||||||
|
`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateFreightTemplate inserts one template.
|
||||||
|
func (r *ProductRepository) CreateFreightTemplate(ctx context.Context, rec FreightTemplateRecord) (*FreightTemplateRecord, error) {
|
||||||
|
if err := requireWriteScope(rec.Scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err := parseID(rec.ID, "template_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rules := rec.RulesJSON
|
||||||
|
if len(rules) == 0 {
|
||||||
|
rules = []byte("{}")
|
||||||
|
}
|
||||||
|
row := r.db.QueryRowContext(ctx, `
|
||||||
|
INSERT INTO product.freight_templates (id, tenant_id, store_id, name, pricing_mode, default_fee, rules_json, status)
|
||||||
|
VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8)
|
||||||
|
RETURNING id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at
|
||||||
|
`, id, rec.Scope.TenantID, rec.Scope.StoreID, rec.Name, rec.PricingMode, nullableInt64(rec.DefaultFee), rules, rec.Status)
|
||||||
|
created, err := scanFreightTemplate(row, rec.Scope)
|
||||||
|
if freightTemplateNameConflictError(err) != nil {
|
||||||
|
return nil, ErrFreightTemplateNameExists
|
||||||
|
}
|
||||||
|
return created, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFreightTemplate loads one non-deleted template.
|
||||||
|
func (r *ProductRepository) GetFreightTemplate(ctx context.Context, templateID string, scope StoreScope) (*FreightTemplateRecord, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err := parseID(templateID, "template_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
row := r.db.QueryRowContext(ctx, `
|
||||||
|
SELECT id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at
|
||||||
|
FROM product.freight_templates
|
||||||
|
WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL
|
||||||
|
`, id, scope.StoreID)
|
||||||
|
rec, err := scanFreightTemplate(row, scope)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrFreightTemplateNotFound
|
||||||
|
}
|
||||||
|
return rec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListFreightTemplates pages templates.
|
||||||
|
func (r *ProductRepository) ListFreightTemplates(ctx context.Context, filter FreightTemplateListFilter, scope StoreScope) ([]FreightTemplateRecord, int64, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
page, pageSize := filter.Page, filter.PageSize
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if pageSize < 1 {
|
||||||
|
pageSize = 20
|
||||||
|
}
|
||||||
|
if pageSize > 100 {
|
||||||
|
pageSize = 100
|
||||||
|
}
|
||||||
|
whereSQL, args := freightTemplateListWhere(filter, scope)
|
||||||
|
var total int64
|
||||||
|
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM product.freight_templates WHERE `+whereSQL, args...).Scan(&total); err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("count freight templates: %w", err)
|
||||||
|
}
|
||||||
|
args = append(args, pageSize, (page-1)*pageSize)
|
||||||
|
rows, err := r.db.QueryContext(ctx, fmt.Sprintf(`
|
||||||
|
SELECT id::text, name, pricing_mode, default_fee, rules_json, status, version, created_at, updated_at, deleted_at
|
||||||
|
FROM product.freight_templates
|
||||||
|
WHERE %s
|
||||||
|
ORDER BY updated_at DESC, id DESC
|
||||||
|
LIMIT $%d OFFSET $%d
|
||||||
|
`, whereSQL, len(args)-1, len(args)), args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("list freight templates: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]FreightTemplateRecord, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
rec, err := scanFreightTemplate(rows, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
out = append(out, *rec)
|
||||||
|
}
|
||||||
|
return out, total, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateFreightTemplate applies a patch.
|
||||||
|
func (r *ProductRepository) UpdateFreightTemplate(ctx context.Context, templateID string, patch FreightTemplatePatch, scope StoreScope) (*FreightTemplateRecord, error) {
|
||||||
|
current, err := r.GetFreightTemplate(ctx, templateID, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if current.Version != patch.ExpectedVersion {
|
||||||
|
return nil, ErrFreightTemplateVersionConflict
|
||||||
|
}
|
||||||
|
id, err := parseID(templateID, "template_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
name := current.Name
|
||||||
|
if patch.Name != nil {
|
||||||
|
name = strings.TrimSpace(*patch.Name)
|
||||||
|
}
|
||||||
|
mode := current.PricingMode
|
||||||
|
if patch.PricingMode != nil {
|
||||||
|
mode = *patch.PricingMode
|
||||||
|
}
|
||||||
|
fee := current.DefaultFee
|
||||||
|
if patch.DefaultFeeSet {
|
||||||
|
fee = patch.DefaultFee
|
||||||
|
}
|
||||||
|
rules := current.RulesJSON
|
||||||
|
if patch.RulesJSON != nil {
|
||||||
|
rules = *patch.RulesJSON
|
||||||
|
}
|
||||||
|
if len(rules) == 0 {
|
||||||
|
rules = []byte("{}")
|
||||||
|
}
|
||||||
|
st := current.Status
|
||||||
|
if patch.Status != nil {
|
||||||
|
st = *patch.Status
|
||||||
|
}
|
||||||
|
res, err := r.db.ExecContext(ctx, `
|
||||||
|
UPDATE product.freight_templates
|
||||||
|
SET name = $1, pricing_mode = $2, default_fee = $3, rules_json = $4::jsonb, status = $5,
|
||||||
|
version = version + 1, updated_at = NOW()
|
||||||
|
WHERE id = $6 AND store_id = $7 AND version = $8 AND deleted_at IS NULL
|
||||||
|
`, name, mode, nullableInt64(fee), rules, st, id, scope.StoreID, patch.ExpectedVersion)
|
||||||
|
if err != nil {
|
||||||
|
if freightTemplateNameConflictError(err) != nil {
|
||||||
|
return nil, ErrFreightTemplateNameExists
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("update freight template: %w", err)
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n == 0 {
|
||||||
|
return nil, ErrFreightTemplateVersionConflict
|
||||||
|
}
|
||||||
|
return r.GetFreightTemplate(ctx, templateID, scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
func freightTemplateListWhere(filter FreightTemplateListFilter, scope StoreScope) (string, []any) {
|
||||||
|
args := []any{scope.StoreID}
|
||||||
|
where := []string{"store_id = $1", "deleted_at IS NULL"}
|
||||||
|
if kw := strings.TrimSpace(filter.Keyword); kw != "" {
|
||||||
|
args = append(args, kw)
|
||||||
|
if filter.ExactMatch {
|
||||||
|
where = append(where, fmt.Sprintf("LOWER(BTRIM(name)) = LOWER($%d)", len(args)))
|
||||||
|
} else {
|
||||||
|
args[len(args)-1] = "%" + kw + "%"
|
||||||
|
where = append(where, fmt.Sprintf("name ILIKE $%d", len(args)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if filter.Status != nil {
|
||||||
|
args = append(args, *filter.Status)
|
||||||
|
where = append(where, fmt.Sprintf("status = $%d", len(args)))
|
||||||
|
}
|
||||||
|
return strings.Join(where, " AND "), args
|
||||||
|
}
|
||||||
|
|
||||||
|
func freightTemplateNameConflictError(err error) error {
|
||||||
|
if isPostgresConstraintError(err, "23505", "uq_freight_templates_store_normalized_name_active") {
|
||||||
|
return ErrFreightTemplateNameExists
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteFreightTemplate soft-deletes when unused.
|
||||||
|
func (r *ProductRepository) DeleteFreightTemplate(ctx context.Context, templateID string, expectedVersion int32, scope StoreScope) (*FreightTemplateRecord, error) {
|
||||||
|
current, err := r.GetFreightTemplate(ctx, templateID, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if current.Version != expectedVersion {
|
||||||
|
return nil, ErrFreightTemplateVersionConflict
|
||||||
|
}
|
||||||
|
id, err := parseID(templateID, "template_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var used bool
|
||||||
|
if err := r.db.QueryRowContext(ctx, `
|
||||||
|
SELECT EXISTS(
|
||||||
|
SELECT 1 FROM product.products
|
||||||
|
WHERE store_id = $1 AND freight_template_id = $2 AND deleted_at IS NULL
|
||||||
|
)`, scope.StoreID, id).Scan(&used); err != nil {
|
||||||
|
return nil, fmt.Errorf("check freight template usage: %w", err)
|
||||||
|
}
|
||||||
|
if used {
|
||||||
|
return nil, ErrFreightTemplateInUse
|
||||||
|
}
|
||||||
|
res, err := r.db.ExecContext(ctx, `
|
||||||
|
UPDATE product.freight_templates
|
||||||
|
SET deleted_at = NOW(), updated_at = NOW(), version = version + 1
|
||||||
|
WHERE id = $1 AND store_id = $2 AND version = $3 AND deleted_at IS NULL
|
||||||
|
`, id, scope.StoreID, expectedVersion)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("delete freight template: %w", err)
|
||||||
|
}
|
||||||
|
n, _ := res.RowsAffected()
|
||||||
|
if n == 0 {
|
||||||
|
return nil, ErrFreightTemplateVersionConflict
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
current.DeletedAt = &now
|
||||||
|
current.Version++
|
||||||
|
return current, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FreightTemplateExists reports whether an enabled/non-deleted template exists in the store.
|
||||||
|
func (r *ProductRepository) FreightTemplateExists(ctx context.Context, templateID string, scope StoreScope) error {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := parseID(templateID, "freight_template_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var ok bool
|
||||||
|
if err := r.db.QueryRowContext(ctx, `
|
||||||
|
SELECT EXISTS(
|
||||||
|
SELECT 1 FROM product.freight_templates
|
||||||
|
WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL AND status = 1
|
||||||
|
)`, id, scope.StoreID).Scan(&ok); err != nil {
|
||||||
|
return fmt.Errorf("validate freight template: %w", err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return ErrFreightTemplateNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type freightScanner interface {
|
||||||
|
Scan(dest ...any) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanFreightTemplate(row freightScanner, scope StoreScope) (*FreightTemplateRecord, error) {
|
||||||
|
var rec FreightTemplateRecord
|
||||||
|
var fee sql.NullInt64
|
||||||
|
var deleted sql.NullTime
|
||||||
|
var rules []byte
|
||||||
|
if err := row.Scan(&rec.ID, &rec.Name, &rec.PricingMode, &fee, &rules, &rec.Status, &rec.Version, &rec.CreatedAt, &rec.UpdatedAt, &deleted); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if fee.Valid {
|
||||||
|
v := fee.Int64
|
||||||
|
rec.DefaultFee = &v
|
||||||
|
}
|
||||||
|
rec.RulesJSON = rules
|
||||||
|
if deleted.Valid {
|
||||||
|
t := deleted.Time
|
||||||
|
rec.DeletedAt = &t
|
||||||
|
}
|
||||||
|
rec.Scope = scope
|
||||||
|
return &rec, nil
|
||||||
|
}
|
||||||
48
internal/repository/freight_template_repository_test.go
Normal file
48
internal/repository/freight_template_repository_test.go
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFreightTemplateListWhereUsesFuzzySearchByDefault(t *testing.T) {
|
||||||
|
where, args := freightTemplateListWhere(FreightTemplateListFilter{Keyword: " 华东 "}, StoreScope{StoreID: 20})
|
||||||
|
if !strings.Contains(where, "name ILIKE $2") {
|
||||||
|
t.Fatalf("where = %q, want fuzzy name predicate", where)
|
||||||
|
}
|
||||||
|
if strings.Contains(where, "LOWER(BTRIM(name))") {
|
||||||
|
t.Fatalf("where = %q, must not use exact predicate by default", where)
|
||||||
|
}
|
||||||
|
if len(args) != 2 || args[0] != int64(20) || args[1] != "%华东%" {
|
||||||
|
t.Fatalf("args = %#v, want [20 %%华东%%]", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFreightTemplateListWhereUsesNormalizedExactSearch(t *testing.T) {
|
||||||
|
status := int32(1)
|
||||||
|
where, args := freightTemplateListWhere(FreightTemplateListFilter{
|
||||||
|
Keyword: " 华东包邮 ", ExactMatch: true, Status: &status,
|
||||||
|
}, StoreScope{StoreID: 20})
|
||||||
|
if !strings.Contains(where, "LOWER(BTRIM(name)) = LOWER($2)") {
|
||||||
|
t.Fatalf("where = %q, want exact normalized name predicate", where)
|
||||||
|
}
|
||||||
|
if strings.Contains(where, "ILIKE") {
|
||||||
|
t.Fatalf("where = %q, must not use fuzzy predicate", where)
|
||||||
|
}
|
||||||
|
if !strings.Contains(where, "status = $3") {
|
||||||
|
t.Fatalf("where = %q, want status predicate", where)
|
||||||
|
}
|
||||||
|
if len(args) != 3 || args[1] != "华东包邮" || args[2] != int32(1) {
|
||||||
|
t.Fatalf("args = %#v, want [20 华东包邮 1]", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFreightTemplateNameConflictError(t *testing.T) {
|
||||||
|
err := &pgconn.PgError{Code: "23505", ConstraintName: "uq_freight_templates_store_normalized_name_active"}
|
||||||
|
if !errors.Is(freightTemplateNameConflictError(err), ErrFreightTemplateNameExists) {
|
||||||
|
t.Fatalf("error = %v, want %v", freightTemplateNameConflictError(err), ErrFreightTemplateNameExists)
|
||||||
|
}
|
||||||
|
}
|
||||||
418
internal/repository/product_batch.go
Normal file
418
internal/repository/product_batch.go
Normal file
@ -0,0 +1,418 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrNoActiveSKU is returned when a product has no sellable/active SKUs for batch price.
|
||||||
|
var ErrNoActiveSKU = errors.New("product has no active sku")
|
||||||
|
|
||||||
|
// ErrInvalidCatalogCategory is returned when a filter target is not a catalog category.
|
||||||
|
var ErrInvalidCatalogCategory = errors.New("category must be an existing catalog category")
|
||||||
|
|
||||||
|
const maxProductBatchSize = 100
|
||||||
|
|
||||||
|
// ValidateCatalogCategory ensures categoryID is a storefront catalog category (node_type=1).
|
||||||
|
func (r *ProductRepository) ValidateCatalogCategory(ctx context.Context, categoryID string, scope StoreScope) error {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := parseID(categoryID, "category_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var nodeType int16
|
||||||
|
err = r.db.QueryRowContext(ctx, `
|
||||||
|
SELECT node_type
|
||||||
|
FROM product.catalog_category
|
||||||
|
WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL
|
||||||
|
`, id, scope.StoreID).Scan(&nodeType)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrInvalidCatalogCategory
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("validate catalog category: %w", err)
|
||||||
|
}
|
||||||
|
if nodeType != 1 {
|
||||||
|
return ErrInvalidCatalogCategory
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBatchProductIDs(productIDs []string) ([]int64, []string, error) {
|
||||||
|
if len(productIDs) == 0 {
|
||||||
|
return nil, nil, errors.New("product_ids is required")
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{}, len(productIDs))
|
||||||
|
unique := make([]string, 0, len(productIDs))
|
||||||
|
for _, raw := range productIDs {
|
||||||
|
id := strings.TrimSpace(raw)
|
||||||
|
if id == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[id]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
unique = append(unique, id)
|
||||||
|
}
|
||||||
|
if len(unique) == 0 {
|
||||||
|
return nil, nil, errors.New("product_ids is required")
|
||||||
|
}
|
||||||
|
if len(unique) > maxProductBatchSize {
|
||||||
|
return nil, nil, fmt.Errorf("product_ids must contain at most %d items", maxProductBatchSize)
|
||||||
|
}
|
||||||
|
parsed := make([]int64, len(unique))
|
||||||
|
for i, id := range unique {
|
||||||
|
n, err := parseID(id, "product_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
parsed[i] = n
|
||||||
|
}
|
||||||
|
return parsed, unique, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func productIDPlaceholders(ids []int64, start int) (string, []any) {
|
||||||
|
placeholders := make([]string, len(ids))
|
||||||
|
args := make([]any, len(ids))
|
||||||
|
for i, id := range ids {
|
||||||
|
placeholders[i] = fmt.Sprintf("$%d", start+i)
|
||||||
|
args[i] = id
|
||||||
|
}
|
||||||
|
return strings.Join(placeholders, ", "), args
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) lockProductsInStore(ctx context.Context, tx *sql.Tx, productIDs []int64, originalIDs []string, scope StoreScope) error {
|
||||||
|
ph, args := productIDPlaceholders(productIDs, 2)
|
||||||
|
queryArgs := append([]any{scope.StoreID}, args...)
|
||||||
|
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
|
||||||
|
SELECT id
|
||||||
|
FROM product.products
|
||||||
|
WHERE store_id = $1
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
AND id IN (%s)
|
||||||
|
FOR UPDATE
|
||||||
|
`, ph), queryArgs...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("lock products: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
found := make(map[int64]struct{}, len(productIDs))
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
return fmt.Errorf("scan locked product: %w", err)
|
||||||
|
}
|
||||||
|
found[id] = struct{}{}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return fmt.Errorf("iterate locked products: %w", err)
|
||||||
|
}
|
||||||
|
for i, id := range productIDs {
|
||||||
|
if _, ok := found[id]; !ok {
|
||||||
|
return fmt.Errorf("%w: %s", ErrProductNotFound, originalIDs[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchUpdateProductStatus sets status for every listed product using the current row version.
|
||||||
|
func (r *ProductRepository) BatchUpdateProductStatus(ctx context.Context, productIDs []string, next productv1.ProductStatus, scope StoreScope) (int32, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if next != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY &&
|
||||||
|
next != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE &&
|
||||||
|
next != productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT {
|
||||||
|
return 0, fmt.Errorf("unsupported product status")
|
||||||
|
}
|
||||||
|
parsed, originals, err := parseBatchProductIDs(productIDs)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("begin batch update product status: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
updated := int32(0)
|
||||||
|
for i, id := range parsed {
|
||||||
|
var previousDBStatus int16
|
||||||
|
var currentVersion int32
|
||||||
|
err := tx.QueryRowContext(ctx, `
|
||||||
|
SELECT status, version
|
||||||
|
FROM product.products
|
||||||
|
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
|
||||||
|
`, id, scope.StoreID).Scan(&previousDBStatus, ¤tVersion)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return 0, fmt.Errorf("%w: %s", ErrProductNotFound, originals[i])
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("load product %s: %w", originals[i], err)
|
||||||
|
}
|
||||||
|
previous := statusFromDB(previousDBStatus)
|
||||||
|
if previous == next {
|
||||||
|
updated++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if next == productv1.ProductStatus_PRODUCT_STATUS_ON_SALE {
|
||||||
|
sellable, err := hasSellableSKU(ctx, tx, id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if !sellable {
|
||||||
|
return 0, fmt.Errorf("cannot put product on sale without a sellable sku: %s", originals[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res, err := tx.ExecContext(ctx, `
|
||||||
|
UPDATE product.products
|
||||||
|
SET status = $2, version = version + 1, updated_at = NOW()
|
||||||
|
WHERE id = $1 AND version = $3 AND deleted_at IS NULL AND store_id = $4
|
||||||
|
`, id, statusToDB(next), currentVersion, scope.StoreID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("update product status %s: %w", originals[i], err)
|
||||||
|
}
|
||||||
|
affected, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("rows affected for %s: %w", originals[i], err)
|
||||||
|
}
|
||||||
|
if affected == 0 {
|
||||||
|
return 0, ErrProductVersionConflict
|
||||||
|
}
|
||||||
|
updated++
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return 0, fmt.Errorf("commit batch update product status: %w", err)
|
||||||
|
}
|
||||||
|
return updated, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchDeleteProducts soft-deletes products and their SKUs in one store transaction.
|
||||||
|
func (r *ProductRepository) BatchDeleteProducts(ctx context.Context, productIDs []string, scope StoreScope) error {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsed, originals, err := parseBatchProductIDs(productIDs)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("begin batch delete products: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ph, args := productIDPlaceholders(parsed, 2)
|
||||||
|
queryArgs := append([]any{scope.StoreID}, args...)
|
||||||
|
res, err := tx.ExecContext(ctx, fmt.Sprintf(`
|
||||||
|
UPDATE product.products
|
||||||
|
SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW()
|
||||||
|
WHERE store_id = $1
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
AND id IN (%s)
|
||||||
|
`, ph), queryArgs...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("batch delete products: %w", err)
|
||||||
|
}
|
||||||
|
affected, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("rows affected: %w", err)
|
||||||
|
}
|
||||||
|
if affected != int64(len(parsed)) {
|
||||||
|
return ErrProductNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
skuPH, skuArgs := productIDPlaceholders(parsed, 1)
|
||||||
|
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
|
||||||
|
UPDATE product.product_items
|
||||||
|
SET deleted_at = COALESCE(deleted_at, NOW()), updated_at = NOW()
|
||||||
|
WHERE deleted_at IS NULL
|
||||||
|
AND product_id IN (%s)
|
||||||
|
`, skuPH), skuArgs...); err != nil {
|
||||||
|
return fmt.Errorf("batch delete product skus: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return fmt.Errorf("commit batch delete products: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchUpdateProductPricesResult counts products and SKUs updated by BatchUpdateProductPrices.
|
||||||
|
type BatchUpdateProductPricesResult struct {
|
||||||
|
UpdatedProductCount int32
|
||||||
|
UpdatedSKUCount int32
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchUpdateProductPrices sets price on every active SKU of the listed products.
|
||||||
|
func (r *ProductRepository) BatchUpdateProductPrices(ctx context.Context, productIDs []string, price int64, scope StoreScope) (*BatchUpdateProductPricesResult, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if price <= 0 {
|
||||||
|
return nil, errors.New("price must be greater than 0")
|
||||||
|
}
|
||||||
|
parsed, originals, err := parseBatchProductIDs(productIDs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("begin batch update product prices: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := &BatchUpdateProductPricesResult{}
|
||||||
|
for i, id := range parsed {
|
||||||
|
res, err := tx.ExecContext(ctx, `
|
||||||
|
UPDATE product.product_items
|
||||||
|
SET price = $2, version = version + 1, updated_at = NOW()
|
||||||
|
WHERE product_id = $1
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
AND is_archived = FALSE
|
||||||
|
`, id, price)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("update sku prices for %s: %w", originals[i], err)
|
||||||
|
}
|
||||||
|
skuCount, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("sku rows affected for %s: %w", originals[i], err)
|
||||||
|
}
|
||||||
|
if skuCount == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrNoActiveSKU, originals[i])
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `
|
||||||
|
UPDATE product.products
|
||||||
|
SET version = version + 1, updated_at = NOW()
|
||||||
|
WHERE id = $1 AND deleted_at IS NULL AND store_id = $2
|
||||||
|
`, id, scope.StoreID); err != nil {
|
||||||
|
return nil, fmt.Errorf("bump product version %s: %w", originals[i], err)
|
||||||
|
}
|
||||||
|
result.UpdatedProductCount++
|
||||||
|
result.UpdatedSKUCount += int32(skuCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return nil, fmt.Errorf("commit batch update product prices: %w", err)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplaceProductsGroup clears all group bindings for the products and binds them to groupID.
|
||||||
|
func (r *ProductRepository) ReplaceProductsGroup(ctx context.Context, productIDs []string, groupID string, bindingIDs []string, scope StoreScope) (int32, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
parsed, originals, err := parseBatchProductIDs(productIDs)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if len(bindingIDs) != len(parsed) {
|
||||||
|
return 0, errors.New("binding ids must match product ids")
|
||||||
|
}
|
||||||
|
parsedGroupID, err := parseID(groupID, "group_id")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
parsedBindingIDs := make([]int64, len(bindingIDs))
|
||||||
|
for i, bindingID := range bindingIDs {
|
||||||
|
parsedBindingIDs[i], err = parseID(bindingID, "category binding id")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("begin replace products group: %w", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
err = tx.QueryRowContext(ctx, `
|
||||||
|
SELECT c.id
|
||||||
|
FROM product.catalog_category AS c
|
||||||
|
WHERE c.id = $1
|
||||||
|
AND c.node_type = 2
|
||||||
|
AND c.store_id = $2
|
||||||
|
AND c.deleted_at IS NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM product.catalog_category child
|
||||||
|
WHERE child.parent_id = c.id
|
||||||
|
AND child.store_id = $2
|
||||||
|
AND child.node_type = 2
|
||||||
|
AND child.deleted_at IS NULL
|
||||||
|
)
|
||||||
|
`, parsedGroupID, scope.StoreID).Scan(&parsedGroupID)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return 0, fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("query group %s: %w", groupID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.lockProductsInStore(ctx, tx, parsed, originals, scope); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ph, args := productIDPlaceholders(parsed, 2)
|
||||||
|
queryArgs := append([]any{scope.StoreID}, args...)
|
||||||
|
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
|
||||||
|
UPDATE product.product_catalog_bindings pcb
|
||||||
|
SET deleted_at = NOW(), updated_at = NOW()
|
||||||
|
FROM product.catalog_category pc
|
||||||
|
WHERE pcb.category_id = pc.id
|
||||||
|
AND pc.node_type = 2
|
||||||
|
AND pc.store_id = $1
|
||||||
|
AND pcb.product_id IN (%s)
|
||||||
|
AND pcb.deleted_at IS NULL
|
||||||
|
AND pc.deleted_at IS NULL
|
||||||
|
`, ph), queryArgs...); err != nil {
|
||||||
|
return 0, fmt.Errorf("clear group bindings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
valuePlaceholders := make([]string, len(parsed))
|
||||||
|
insertArgs := make([]any, 0, len(parsed)*3)
|
||||||
|
for i, productID := range parsed {
|
||||||
|
base := i * 3
|
||||||
|
valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3)
|
||||||
|
insertArgs = append(insertArgs, parsedBindingIDs[i], productID, parsedGroupID)
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`
|
||||||
|
INSERT INTO product.product_catalog_bindings (id, product_id, category_id)
|
||||||
|
VALUES %s
|
||||||
|
ON CONFLICT (product_id, category_id) WHERE deleted_at IS NULL DO NOTHING
|
||||||
|
`, strings.Join(valuePlaceholders, ", ")), insertArgs...); err != nil {
|
||||||
|
return 0, fmt.Errorf("insert group bindings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return 0, fmt.Errorf("commit replace products group: %w", err)
|
||||||
|
}
|
||||||
|
return int32(len(parsed)), nil
|
||||||
|
}
|
||||||
40
internal/repository/product_batch_test.go
Normal file
40
internal/repository/product_batch_test.go
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseBatchProductIDs(t *testing.T) {
|
||||||
|
parsed, unique, err := parseBatchProductIDs([]string{" 11111 ", "11111", "22222"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parseBatchProductIDs() error = %v", err)
|
||||||
|
}
|
||||||
|
if len(unique) != 2 || unique[0] != "11111" || unique[1] != "22222" {
|
||||||
|
t.Fatalf("unique = %v, want [11111 22222]", unique)
|
||||||
|
}
|
||||||
|
if len(parsed) != 2 || parsed[0] != 11111 || parsed[1] != 22222 {
|
||||||
|
t.Fatalf("parsed = %v, want [11111 22222]", parsed)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, _, err := parseBatchProductIDs(nil); err == nil {
|
||||||
|
t.Fatal("parseBatchProductIDs(nil) error = nil, want required")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductIDPlaceholders(t *testing.T) {
|
||||||
|
ids := []int64{11111, 22222}
|
||||||
|
|
||||||
|
gotPlaceholders, gotArgs := productIDPlaceholders(ids, 1)
|
||||||
|
if gotPlaceholders != "$1, $2" {
|
||||||
|
t.Fatalf("placeholders starting at 1 = %q, want %q", gotPlaceholders, "$1, $2")
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(gotArgs, []any{int64(11111), int64(22222)}) {
|
||||||
|
t.Fatalf("args = %v, want [11111 22222]", gotArgs)
|
||||||
|
}
|
||||||
|
|
||||||
|
gotPlaceholders, _ = productIDPlaceholders(ids, 2)
|
||||||
|
if gotPlaceholders != "$2, $3" {
|
||||||
|
t.Fatalf("placeholders starting at 2 = %q, want %q", gotPlaceholders, "$2, $3")
|
||||||
|
}
|
||||||
|
}
|
||||||
717
internal/repository/product_category_repository.go
Normal file
717
internal/repository/product_category_repository.go
Normal file
@ -0,0 +1,717 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrProductCategoryNotFound = errors.New("product category not found")
|
||||||
|
ErrProductCategoryVersionConflict = errors.New("product category version conflict")
|
||||||
|
ErrDuplicateProductCategory = errors.New("duplicate product category name")
|
||||||
|
ErrDuplicatePlatformCategory = errors.New("duplicate platform category id")
|
||||||
|
)
|
||||||
|
|
||||||
|
type ProductCategoryRecord struct {
|
||||||
|
ID, Name, ParentID, RuleID, Extra, CertStatusMsg string
|
||||||
|
Level, Priority, Status, CategoryType, CertStatusCode, Version int32
|
||||||
|
PlatformCategoryID, PlatformParentCategoryID int64
|
||||||
|
ChannelList []int32
|
||||||
|
HasChildren, HasPropRequired, CertStatusPass bool
|
||||||
|
ProductCount int64
|
||||||
|
CreatedAt, UpdatedAt time.Time
|
||||||
|
DeletedAt *time.Time
|
||||||
|
Children []*ProductCategoryRecord
|
||||||
|
Path []ProductCategoryPathNodeRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProductCategoryListFilter narrows a standard-category list query. The
|
||||||
|
// fields are combined when more than one selector is supplied.
|
||||||
|
type ProductCategoryListFilter struct {
|
||||||
|
ProductCategoryID string
|
||||||
|
PlatformCategoryID *int64
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProductCategoryPatch struct {
|
||||||
|
ID string
|
||||||
|
ExpectedVersion int32
|
||||||
|
Name, RuleID, Extra, CertStatusMsg *string
|
||||||
|
Priority, Status, CategoryType, CertStatusCode *int32
|
||||||
|
ChannelList *[]int32
|
||||||
|
HasChildren, HasPropRequired, CertStatusPass *bool
|
||||||
|
Children []*ProductCategoryPatch
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProductCategoryDeleteResult struct {
|
||||||
|
CategoryIDs []string
|
||||||
|
CategoryCount, BindingCount, ProductCount int32
|
||||||
|
DeletedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) ValidateProductCategory(ctx context.Context, categoryID string, scope StoreScope) error {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := parseID(categoryID, "category_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var exists bool
|
||||||
|
if err := r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND deleted_at IS NULL)`, id).Scan(&exists); err != nil {
|
||||||
|
return fmt.Errorf("validate product category: %w", err)
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return ErrProductCategoryNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) CreateProductCategory(ctx context.Context, root *ProductCategoryRecord) (*ProductCategoryRecord, error) {
|
||||||
|
if root == nil {
|
||||||
|
return nil, errors.New("product category is required")
|
||||||
|
}
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
created, err := createProductCategoryNode(ctx, tx, root, root.ParentID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return created, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func createProductCategoryNode(ctx context.Context, tx *sql.Tx, input *ProductCategoryRecord, parentID string) (*ProductCategoryRecord, error) {
|
||||||
|
level := int32(1)
|
||||||
|
parent := sql.NullInt64{}
|
||||||
|
if strings.TrimSpace(parentID) != "" {
|
||||||
|
id, err := parseID(parentID, "parent_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var parentLevel int32
|
||||||
|
var parentPlatformCategoryID int64
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT level,platform_category_id FROM product.product_category WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, id).Scan(&parentLevel, &parentPlatformCategoryID); errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrProductCategoryNotFound
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if input.PlatformParentCategoryID != parentPlatformCategoryID {
|
||||||
|
return nil, errors.New("platform_parent_category_id must equal the local parent's platform_category_id")
|
||||||
|
}
|
||||||
|
parent = sql.NullInt64{Int64: id, Valid: true}
|
||||||
|
level = parentLevel + 1
|
||||||
|
}
|
||||||
|
id, err := parseID(input.ID, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
row := tx.QueryRowContext(ctx, `INSERT INTO product.product_category (id,parent_id,level,name,priority,rule_id,status,category_type,channel_list,has_children,has_prop_required,extra,cert_status_code,cert_status_pass,cert_status_msg,platform_category_id,platform_parent_category_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17) RETURNING id,parent_id,level,name,priority,rule_id,status,category_type,channel_list,has_children,has_prop_required,extra,cert_status_code,cert_status_pass,cert_status_msg,platform_category_id,platform_parent_category_id,version,created_at,updated_at,deleted_at,0::bigint`, id, parent, level, input.Name, input.Priority, input.RuleID, input.Status, input.CategoryType, input.ChannelList, input.HasChildren, input.HasPropRequired, input.Extra, input.CertStatusCode, input.CertStatusPass, input.CertStatusMsg, input.PlatformCategoryID, input.PlatformParentCategoryID)
|
||||||
|
created, err := scanProductCategory(row)
|
||||||
|
if err != nil {
|
||||||
|
return nil, mapProductCategoryWriteError(err)
|
||||||
|
}
|
||||||
|
for _, child := range input.Children {
|
||||||
|
value, err := createProductCategoryNode(ctx, tx, child, created.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
created.Children = append(created.Children, value)
|
||||||
|
}
|
||||||
|
return created, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) ListProductCategories(ctx context.Context, filter ProductCategoryListFilter) ([]*ProductCategoryRecord, error) {
|
||||||
|
id := strings.TrimSpace(filter.ProductCategoryID)
|
||||||
|
name := strings.TrimSpace(filter.Name)
|
||||||
|
if id != "" && filter.PlatformCategoryID == nil && name == "" {
|
||||||
|
node, err := r.loadProductCategoryOneLevel(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := []*ProductCategoryRecord{node}
|
||||||
|
return out, r.populateProductCategoryPaths(ctx, flattenProductCategoryNodes(out))
|
||||||
|
}
|
||||||
|
if id != "" || filter.PlatformCategoryID != nil || name != "" {
|
||||||
|
out, err := r.searchProductCategories(ctx, filter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, r.populateProductCategoryPaths(ctx, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := r.db.QueryContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE c.parent_id IS NULL AND c.deleted_at IS NULL ORDER BY c.priority,c.id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]*ProductCategoryRecord, 0)
|
||||||
|
byID := make(map[string]*ProductCategoryRecord)
|
||||||
|
for rows.Next() {
|
||||||
|
node, err := scanProductCategory(rows)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, node)
|
||||||
|
byID[node.ID] = node
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(byID) == 0 {
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
children, err := r.db.QueryContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c JOIN product.product_category p ON p.id=c.parent_id WHERE c.deleted_at IS NULL AND p.parent_id IS NULL AND p.deleted_at IS NULL ORDER BY p.priority,p.id,c.priority,c.id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer children.Close()
|
||||||
|
for children.Next() {
|
||||||
|
child, err := scanProductCategory(children)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if parent := byID[child.ParentID]; parent != nil {
|
||||||
|
parent.Children = append(parent.Children, child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := children.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, r.populateProductCategoryPaths(ctx, flattenProductCategoryNodes(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) searchProductCategories(ctx context.Context, filter ProductCategoryListFilter) ([]*ProductCategoryRecord, error) {
|
||||||
|
clauses := []string{"c.deleted_at IS NULL"}
|
||||||
|
args := make([]any, 0, 3)
|
||||||
|
if id := strings.TrimSpace(filter.ProductCategoryID); id != "" {
|
||||||
|
parsed, err := parseID(id, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
args = append(args, parsed)
|
||||||
|
clauses = append(clauses, fmt.Sprintf("c.id=$%d", len(args)))
|
||||||
|
}
|
||||||
|
if filter.PlatformCategoryID != nil {
|
||||||
|
args = append(args, *filter.PlatformCategoryID)
|
||||||
|
clauses = append(clauses, fmt.Sprintf("c.platform_category_id=$%d", len(args)))
|
||||||
|
}
|
||||||
|
if name := strings.TrimSpace(filter.Name); name != "" {
|
||||||
|
args = append(args, "%"+escapeLikeLiteral(name)+"%")
|
||||||
|
clauses = append(clauses, fmt.Sprintf("lower(c.name) LIKE lower($%d) ESCAPE '\\'", len(args)))
|
||||||
|
}
|
||||||
|
rows, err := r.db.QueryContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE `+strings.Join(clauses, " AND ")+` ORDER BY c.level,c.priority,c.id`, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make([]*ProductCategoryRecord, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
node, err := scanProductCategory(rows)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, node)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func flattenProductCategoryNodes(roots []*ProductCategoryRecord) []*ProductCategoryRecord {
|
||||||
|
out := make([]*ProductCategoryRecord, 0, len(roots))
|
||||||
|
for _, root := range roots {
|
||||||
|
if root == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, root)
|
||||||
|
out = append(out, root.Children...)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// populateProductCategoryPaths loads each supplied node's active ancestors in
|
||||||
|
// one recursive query. The returned path is always ordered from root to node.
|
||||||
|
func (r *ProductRepository) populateProductCategoryPaths(ctx context.Context, categories []*ProductCategoryRecord) error {
|
||||||
|
if len(categories) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ids := make([]int64, 0, len(categories))
|
||||||
|
byID := make(map[string]*ProductCategoryRecord, len(categories))
|
||||||
|
for _, category := range categories {
|
||||||
|
if category == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parsed, err := parseID(category.ID, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ids = append(ids, parsed)
|
||||||
|
byID[category.ID] = category
|
||||||
|
category.Path = []ProductCategoryPathNodeRecord{}
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
placeholders, args := productIDPlaceholders(ids, 1)
|
||||||
|
rows, err := r.db.QueryContext(ctx, `
|
||||||
|
WITH RECURSIVE category_paths AS (
|
||||||
|
SELECT c.id AS target_category_id,
|
||||||
|
c.id,
|
||||||
|
c.parent_id,
|
||||||
|
c.name,
|
||||||
|
c.level,
|
||||||
|
0 AS depth,
|
||||||
|
ARRAY[c.id] AS visited_category_ids
|
||||||
|
FROM product.product_category c
|
||||||
|
WHERE c.id IN (`+placeholders+`)
|
||||||
|
AND c.deleted_at IS NULL
|
||||||
|
UNION ALL
|
||||||
|
SELECT cp.target_category_id,
|
||||||
|
parent.id,
|
||||||
|
parent.parent_id,
|
||||||
|
parent.name,
|
||||||
|
parent.level,
|
||||||
|
cp.depth + 1,
|
||||||
|
cp.visited_category_ids || parent.id
|
||||||
|
FROM category_paths cp
|
||||||
|
JOIN product.product_category parent ON parent.id = cp.parent_id
|
||||||
|
WHERE parent.deleted_at IS NULL
|
||||||
|
AND NOT parent.id = ANY(cp.visited_category_ids)
|
||||||
|
)
|
||||||
|
SELECT target_category_id, id, parent_id, name, level
|
||||||
|
FROM category_paths
|
||||||
|
ORDER BY target_category_id, depth DESC`, args...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("list product category paths: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var targetID, categoryID int64
|
||||||
|
var parentID sql.NullInt64
|
||||||
|
var name string
|
||||||
|
var level int32
|
||||||
|
if err := rows.Scan(&targetID, &categoryID, &parentID, &name, &level); err != nil {
|
||||||
|
return fmt.Errorf("scan product category path: %w", err)
|
||||||
|
}
|
||||||
|
if target := byID[formatID(targetID)]; target != nil {
|
||||||
|
target.Path = append(target.Path, ProductCategoryPathNodeRecord{
|
||||||
|
ID: formatID(categoryID), Name: name, Level: level, ParentID: nullableFormattedID(parentID),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return fmt.Errorf("iterate product category paths: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) loadProductCategoryOneLevel(ctx context.Context, id string) (*ProductCategoryRecord, error) {
|
||||||
|
parsed, err := parseID(id, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
root, err := scanProductCategory(r.db.QueryRowContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE c.id=$1 AND c.deleted_at IS NULL`, parsed))
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrProductCategoryNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rows, err := r.db.QueryContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE c.parent_id=$1 AND c.deleted_at IS NULL ORDER BY c.priority,c.id`, parsed)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
child, err := scanProductCategory(rows)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
root.Children = append(root.Children, child)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return root, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) GetProductCategory(ctx context.Context, id string) (*ProductCategoryRecord, error) {
|
||||||
|
return r.loadProductCategoryTree(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
const productCategoryColumns = `c.id,c.parent_id,c.level,c.name,c.priority,c.rule_id,c.status,c.category_type,c.channel_list,c.has_children,c.has_prop_required,c.extra,c.cert_status_code,c.cert_status_pass,c.cert_status_msg,c.platform_category_id,c.platform_parent_category_id,c.version,c.created_at,c.updated_at,c.deleted_at,(SELECT COUNT(*) FROM product.product_category_bindings b WHERE b.product_category_id=c.id AND b.deleted_at IS NULL)`
|
||||||
|
|
||||||
|
func (r *ProductRepository) loadProductCategoryTree(ctx context.Context, id string) (*ProductCategoryRecord, error) {
|
||||||
|
parsed, err := parseID(id, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
root, err := scanProductCategory(r.db.QueryRowContext(ctx, `SELECT `+productCategoryColumns+` FROM product.product_category c WHERE c.id=$1 AND c.deleted_at IS NULL`, parsed))
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrProductCategoryNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rows, err := r.db.QueryContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE parent_id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT `+productCategoryColumns+` FROM product.product_category c JOIN d ON d.id=c.id ORDER BY c.level,c.priority,c.id`, parsed)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
byID := map[string]*ProductCategoryRecord{root.ID: root}
|
||||||
|
for rows.Next() {
|
||||||
|
node, e := scanProductCategory(rows)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
byID[node.ID] = node
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, node := range byID {
|
||||||
|
if node.ParentID != "" {
|
||||||
|
if parent := byID[node.ParentID]; parent != nil {
|
||||||
|
parent.Children = append(parent.Children, node)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sortProductCategoryTree(root)
|
||||||
|
return root, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) UpdateProductCategory(ctx context.Context, rootID string, patch *ProductCategoryPatch) (*ProductCategoryRecord, error) {
|
||||||
|
if patch == nil {
|
||||||
|
return nil, errors.New("product category patch is required")
|
||||||
|
}
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
root, err := parseID(rootID, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var exists bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND deleted_at IS NULL)`, root).Scan(&exists); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return nil, ErrProductCategoryNotFound
|
||||||
|
}
|
||||||
|
if err := updateProductCategoryPatch(ctx, tx, root, patch); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.GetProductCategory(ctx, rootID)
|
||||||
|
}
|
||||||
|
func updateProductCategoryPatch(ctx context.Context, tx *sql.Tx, root int64, patch *ProductCategoryPatch) error {
|
||||||
|
id, err := parseID(patch.ID, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var allowed bool
|
||||||
|
if err = tx.QueryRowContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT EXISTS(SELECT 1 FROM d WHERE id=$2)`, root, id).Scan(&allowed); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !allowed {
|
||||||
|
return errors.New("updated category must be a descendant of the request root")
|
||||||
|
}
|
||||||
|
var channelList any
|
||||||
|
if patch.ChannelList != nil {
|
||||||
|
channelList = *patch.ChannelList
|
||||||
|
}
|
||||||
|
result, err := tx.ExecContext(ctx, `UPDATE product.product_category SET name=COALESCE($1,name),priority=COALESCE($2,priority),rule_id=COALESCE($3,rule_id),status=COALESCE($4,status),category_type=COALESCE($5,category_type),channel_list=CASE WHEN $6 THEN $7 ELSE channel_list END,has_children=COALESCE($8,has_children),has_prop_required=COALESCE($9,has_prop_required),extra=COALESCE($10,extra),cert_status_code=COALESCE($11,cert_status_code),cert_status_pass=COALESCE($12,cert_status_pass),cert_status_msg=COALESCE($13,cert_status_msg),version=version+1,updated_at=NOW() WHERE id=$14 AND version=$15 AND deleted_at IS NULL`, patch.Name, patch.Priority, patch.RuleID, patch.Status, patch.CategoryType, patch.ChannelList != nil, channelList, patch.HasChildren, patch.HasPropRequired, patch.Extra, patch.CertStatusCode, patch.CertStatusPass, patch.CertStatusMsg, id, patch.ExpectedVersion)
|
||||||
|
if err != nil {
|
||||||
|
return mapProductCategoryWriteError(err)
|
||||||
|
}
|
||||||
|
n, _ := result.RowsAffected()
|
||||||
|
if n == 0 {
|
||||||
|
return ErrProductCategoryVersionConflict
|
||||||
|
}
|
||||||
|
for _, child := range patch.Children {
|
||||||
|
if err := updateProductCategoryPatch(ctx, tx, root, child); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) DeleteProductCategory(ctx context.Context, id string, expected int32) (*ProductCategoryDeleteResult, error) {
|
||||||
|
parsed, err := parseID(id, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var version int32
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT version FROM product.product_category WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, parsed).Scan(&version); errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, ErrProductCategoryNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if version != expected {
|
||||||
|
return nil, ErrProductCategoryVersionConflict
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `WITH RECURSIVE d AS (SELECT id FROM product.product_category WHERE id=$1 AND deleted_at IS NULL UNION ALL SELECT c.id FROM product.product_category c JOIN d ON c.parent_id=d.id WHERE c.deleted_at IS NULL) SELECT id FROM d ORDER BY id`, parsed)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var ids []int64
|
||||||
|
for rows.Next() {
|
||||||
|
var v int64
|
||||||
|
if err = rows.Scan(&v); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ids = append(ids, v)
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if err = rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
q, args := int64In("product_category_id", ids, 1)
|
||||||
|
var bindings, products int32
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT COUNT(*),COUNT(DISTINCT product_id) FROM product.product_category_bindings WHERE `+q+` AND deleted_at IS NULL`, args...).Scan(&bindings, &products); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NOW(),updated_at=NOW() WHERE `+q+` AND deleted_at IS NULL`, args...); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
q, args = int64In("id", ids, 1)
|
||||||
|
var deleted time.Time
|
||||||
|
if err = tx.QueryRowContext(ctx, `UPDATE product.product_category SET deleted_at=NOW(),updated_at=NOW(),version=version+1 WHERE `+q+` RETURNING deleted_at`, args...).Scan(&deleted); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]string, len(ids))
|
||||||
|
for i, v := range ids {
|
||||||
|
out[i] = formatID(v)
|
||||||
|
}
|
||||||
|
return &ProductCategoryDeleteResult{CategoryIDs: out, CategoryCount: int32(len(ids)), BindingCount: bindings, ProductCount: products, DeletedAt: deleted}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProductRepository) BindProductsToProductCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) (int32, int32, error) {
|
||||||
|
if len(productIDs) == 0 {
|
||||||
|
return 0, 0, errors.New("product_ids is required")
|
||||||
|
}
|
||||||
|
category, err := parseID(categoryID, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
tx, err := r.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var enabled bool
|
||||||
|
if err = tx.QueryRowContext(ctx, `SELECT status=1 AND NOT EXISTS(SELECT 1 FROM product.product_category child WHERE child.parent_id=c.id AND child.deleted_at IS NULL) FROM product.product_category c WHERE c.id=$1 AND c.deleted_at IS NULL FOR UPDATE`, category).Scan(&enabled); errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return 0, 0, ErrProductCategoryNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
if !enabled {
|
||||||
|
return 0, 0, errors.New("product category must be enabled and terminal")
|
||||||
|
}
|
||||||
|
var bound, already int32
|
||||||
|
for i, raw := range productIDs {
|
||||||
|
product, e := parseID(raw, "product_id")
|
||||||
|
if e != nil {
|
||||||
|
return 0, 0, e
|
||||||
|
}
|
||||||
|
var exists bool
|
||||||
|
if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.products WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, scope.TenantID, scope.StoreID).Scan(&exists); e != nil {
|
||||||
|
return 0, 0, e
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return 0, 0, ErrProductNotFound
|
||||||
|
}
|
||||||
|
var active bool
|
||||||
|
if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, category, scope.StoreID).Scan(&active); e != nil {
|
||||||
|
return 0, 0, e
|
||||||
|
}
|
||||||
|
if active {
|
||||||
|
already++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, e = tx.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NULL,updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND store_id=$3 AND deleted_at IS NOT NULL`, product, category, scope.StoreID); e != nil {
|
||||||
|
return 0, 0, e
|
||||||
|
}
|
||||||
|
var restored bool
|
||||||
|
if e = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category_bindings WHERE product_id=$1 AND product_category_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, category, scope.StoreID).Scan(&restored); e != nil {
|
||||||
|
return 0, 0, e
|
||||||
|
}
|
||||||
|
if !restored {
|
||||||
|
binding, e := parseID(bindingIDs[i], "product_category_binding_id")
|
||||||
|
if e != nil {
|
||||||
|
return 0, 0, e
|
||||||
|
}
|
||||||
|
if _, e = tx.ExecContext(ctx, `INSERT INTO product.product_category_bindings(id,tenant_id,store_id,product_id,product_category_id) VALUES($1,$2,$3,$4,$5)`, binding, scope.TenantID, scope.StoreID, product, category); e != nil {
|
||||||
|
return 0, 0, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bound++
|
||||||
|
}
|
||||||
|
if err = tx.Commit(); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
return bound, already, nil
|
||||||
|
}
|
||||||
|
func (r *ProductRepository) UnbindProductsFromProductCategory(ctx context.Context, categoryID string, productIDs []string, scope StoreScope) (int32, error) {
|
||||||
|
if err := requireWriteScope(scope); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
category, err := parseID(categoryID, "product_category_id")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
var exists bool
|
||||||
|
if err = r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.product_category WHERE id=$1 AND deleted_at IS NULL)`, category).Scan(&exists); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return 0, ErrProductCategoryNotFound
|
||||||
|
}
|
||||||
|
var count int32
|
||||||
|
for _, raw := range productIDs {
|
||||||
|
product, e := parseID(raw, "product_id")
|
||||||
|
if e != nil {
|
||||||
|
return 0, e
|
||||||
|
}
|
||||||
|
var productExists bool
|
||||||
|
if e = r.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM product.products WHERE id=$1 AND tenant_id=$2 AND store_id=$3 AND deleted_at IS NULL)`, product, scope.TenantID, scope.StoreID).Scan(&productExists); e != nil {
|
||||||
|
return 0, e
|
||||||
|
}
|
||||||
|
if !productExists {
|
||||||
|
return 0, ErrProductNotFound
|
||||||
|
}
|
||||||
|
result, e := r.db.ExecContext(ctx, `UPDATE product.product_category_bindings SET deleted_at=NOW(),updated_at=NOW() WHERE product_id=$1 AND product_category_id=$2 AND tenant_id=$3 AND store_id=$4 AND deleted_at IS NULL`, product, category, scope.TenantID, scope.StoreID)
|
||||||
|
if e != nil {
|
||||||
|
return 0, e
|
||||||
|
}
|
||||||
|
n, _ := result.RowsAffected()
|
||||||
|
count += int32(n)
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type productCategoryScanner interface{ Scan(...any) error }
|
||||||
|
|
||||||
|
// postgresInt32Array adapts PostgreSQL INTEGER[] values returned by pgx's
|
||||||
|
// database/sql driver (as "{1,6}") to the protobuf-facing []int32 field.
|
||||||
|
// database/sql cannot scan that textual value directly into []int32.
|
||||||
|
type postgresInt32Array []int32
|
||||||
|
|
||||||
|
func (values *postgresInt32Array) Scan(source any) error {
|
||||||
|
if source == nil {
|
||||||
|
*values = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
switch value := source.(type) {
|
||||||
|
case string:
|
||||||
|
raw = value
|
||||||
|
case []byte:
|
||||||
|
raw = string(value)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported PostgreSQL integer array type %T", source)
|
||||||
|
}
|
||||||
|
raw = strings.TrimSpace(raw)
|
||||||
|
if raw == "{}" {
|
||||||
|
*values = []int32{}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(raw) < 2 || raw[0] != '{' || raw[len(raw)-1] != '}' {
|
||||||
|
return fmt.Errorf("invalid PostgreSQL integer array %q", raw)
|
||||||
|
}
|
||||||
|
parts := strings.Split(raw[1:len(raw)-1], ",")
|
||||||
|
parsed := make([]int32, 0, len(parts))
|
||||||
|
for _, part := range parts {
|
||||||
|
value, err := strconv.ParseInt(strings.TrimSpace(part), 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("parse PostgreSQL integer array element %q: %w", part, err)
|
||||||
|
}
|
||||||
|
parsed = append(parsed, int32(value))
|
||||||
|
}
|
||||||
|
*values = parsed
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanProductCategory(row productCategoryScanner) (*ProductCategoryRecord, error) {
|
||||||
|
var id sql.NullInt64
|
||||||
|
var parent sql.NullInt64
|
||||||
|
var deleted sql.NullTime
|
||||||
|
var channelList postgresInt32Array
|
||||||
|
value := &ProductCategoryRecord{}
|
||||||
|
if err := row.Scan(&id, &parent, &value.Level, &value.Name, &value.Priority, &value.RuleID, &value.Status, &value.CategoryType, &channelList, &value.HasChildren, &value.HasPropRequired, &value.Extra, &value.CertStatusCode, &value.CertStatusPass, &value.CertStatusMsg, &value.PlatformCategoryID, &value.PlatformParentCategoryID, &value.Version, &value.CreatedAt, &value.UpdatedAt, &deleted, &value.ProductCount); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
value.ChannelList = []int32(channelList)
|
||||||
|
value.ID = formatID(id.Int64)
|
||||||
|
if parent.Valid {
|
||||||
|
value.ParentID = formatID(parent.Int64)
|
||||||
|
}
|
||||||
|
if deleted.Valid {
|
||||||
|
value.DeletedAt = &deleted.Time
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
func sortProductCategoryTree(node *ProductCategoryRecord) {
|
||||||
|
if node == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, child := range node.Children {
|
||||||
|
sortProductCategoryTree(child)
|
||||||
|
}
|
||||||
|
sort.Slice(node.Children, func(i, j int) bool {
|
||||||
|
if node.Children[i].Priority == node.Children[j].Priority {
|
||||||
|
return node.Children[i].ID < node.Children[j].ID
|
||||||
|
}
|
||||||
|
return node.Children[i].Priority < node.Children[j].Priority
|
||||||
|
})
|
||||||
|
}
|
||||||
|
func int64In(column string, values []int64, start int) (string, []any) {
|
||||||
|
parts := make([]string, len(values))
|
||||||
|
args := make([]any, len(values))
|
||||||
|
for i, value := range values {
|
||||||
|
parts[i] = fmt.Sprintf("$%d", start+i)
|
||||||
|
args[i] = value
|
||||||
|
}
|
||||||
|
return column + " IN (" + strings.Join(parts, ",") + ")", args
|
||||||
|
}
|
||||||
|
func mapProductCategoryWriteError(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "uq_product_category_active_parent_name") {
|
||||||
|
return ErrDuplicateProductCategory
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "uq_product_category_active_platform_category") {
|
||||||
|
return ErrDuplicatePlatformCategory
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
60
internal/repository/product_presale_migration.go
Normal file
60
internal/repository/product_presale_migration.go
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
productPresaleMigrationFile = "008_product_presale_delivery_purchase_limit.sql"
|
||||||
|
productPresaleMigrationLockID = 904_120_008
|
||||||
|
)
|
||||||
|
|
||||||
|
// ApplyProductPresaleMigration executes the release SQL before the product
|
||||||
|
// service begins serving traffic. The migration itself is idempotent; the
|
||||||
|
// advisory lock only serializes concurrent replicas during deployment.
|
||||||
|
func ApplyProductPresaleMigration(ctx context.Context, db *sql.DB) error {
|
||||||
|
if db == nil {
|
||||||
|
return fmt.Errorf("database is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
ddl, err := readProductPresaleMigration()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := db.Conn(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("acquire product presale migration connection: %w", err)
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock($1)", productPresaleMigrationLockID); err != nil {
|
||||||
|
return fmt.Errorf("lock product presale migration: %w", err)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_, _ = conn.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", productPresaleMigrationLockID)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if _, err := conn.ExecContext(ctx, string(ddl)); err != nil {
|
||||||
|
return fmt.Errorf("apply product presale migration: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readProductPresaleMigration() ([]byte, error) {
|
||||||
|
paths := []string{
|
||||||
|
"scripts/sql/" + productPresaleMigrationFile,
|
||||||
|
"/app/migrations/" + productPresaleMigrationFile,
|
||||||
|
}
|
||||||
|
var lastErr error
|
||||||
|
for _, path := range paths {
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err == nil {
|
||||||
|
return contents, nil
|
||||||
|
}
|
||||||
|
lastErr = err
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("read product presale migration: %w", lastErr)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,11 @@
|
|||||||
package repository
|
package repository
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
func TestEscapeLikeLiteral(t *testing.T) {
|
func TestEscapeLikeLiteral(t *testing.T) {
|
||||||
input := `100%_off\\bundle`
|
input := `100%_off\\bundle`
|
||||||
@ -37,3 +42,60 @@ func TestAggregateInventoryAdjustmentsRejectsInvalidSKUID(t *testing.T) {
|
|||||||
t.Fatal("expected invalid sku id error")
|
t.Fatal("expected invalid sku id error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReplaceProductLeafCategoryBindingsRequiresStoreScope(t *testing.T) {
|
||||||
|
err := replaceProductLeafCategoryBindings(nil, nil, "1001", []string{"2001"}, []string{"3001"}, StoreScope{})
|
||||||
|
if err != ErrStoreScopeRequired {
|
||||||
|
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReplaceProductGroupBindingsRequiresStoreScope(t *testing.T) {
|
||||||
|
err := replaceProductGroupBindings(nil, nil, "1001", []string{"2001"}, []string{"3001"}, StoreScope{})
|
||||||
|
if err != ErrStoreScopeRequired {
|
||||||
|
t.Fatalf("err = %v, want %v", err, ErrStoreScopeRequired)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductListWhereUsesBusinessProductCategoryTree(t *testing.T) {
|
||||||
|
where, args := productListWhere(ProductListFilter{ProductCategoryID: "2001"}, StoreScope{StoreID: 1001})
|
||||||
|
for _, expected := range []string{
|
||||||
|
"WITH RECURSIVE category_descendants",
|
||||||
|
"product.product_category c",
|
||||||
|
"product.product_category_bindings pcb",
|
||||||
|
"pcb.product_category_id",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(where, expected) {
|
||||||
|
t.Fatalf("category predicate missing %q:\n%s", expected, where)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(where, "product.product_catalog_bindings") {
|
||||||
|
t.Fatalf("category predicate must not query storefront catalog bindings:\n%s", where)
|
||||||
|
}
|
||||||
|
if len(args) != 2 || args[0] != int64(1001) || args[1] != "2001" {
|
||||||
|
t.Fatalf("args = %#v, want [1001 2001]", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductListWhereFiltersStatus(t *testing.T) {
|
||||||
|
productStatus := productv1.ProductStatus_PRODUCT_STATUS_INVENTORY
|
||||||
|
where, args := productListWhere(ProductListFilter{Status: &productStatus}, StoreScope{StoreID: 1001})
|
||||||
|
if !strings.Contains(where, "p.status = $2") {
|
||||||
|
t.Fatalf("status predicate missing:\n%s", where)
|
||||||
|
}
|
||||||
|
if len(args) != 2 || args[1] != int16(1) {
|
||||||
|
t.Fatalf("args = %#v, want [1001 1]", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductListWhereIgnoresSoftDeletedGroupBindings(t *testing.T) {
|
||||||
|
where, _ := productListWhere(ProductListFilter{GroupID: "2001"}, StoreScope{StoreID: 1001})
|
||||||
|
for _, expected := range []string{
|
||||||
|
"pcb.deleted_at IS NULL",
|
||||||
|
"pc.deleted_at IS NULL",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(where, expected) {
|
||||||
|
t.Fatalf("group predicate missing %q:\n%s", expected, where)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
24
internal/repository/store_scope.go
Normal file
24
internal/repository/store_scope.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
// ErrStoreScopeRequired is returned when a store-scoped write or list has no shop.
|
||||||
|
var ErrStoreScopeRequired = errors.New("store scope is required")
|
||||||
|
|
||||||
|
// StoreScope identifies the shop for a repository call.
|
||||||
|
type StoreScope struct {
|
||||||
|
TenantID int64
|
||||||
|
StoreID int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valid reports whether both tenant and store identifiers are present.
|
||||||
|
func (s StoreScope) Valid() bool {
|
||||||
|
return s.TenantID > 0 && s.StoreID > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireWriteScope(scope StoreScope) error {
|
||||||
|
if !scope.Valid() {
|
||||||
|
return ErrStoreScopeRequired
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
33
internal/repository/store_scope_test.go
Normal file
33
internal/repository/store_scope_test.go
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStoreScopeValid(t *testing.T) {
|
||||||
|
if (StoreScope{}).Valid() {
|
||||||
|
t.Fatal("empty scope must be invalid")
|
||||||
|
}
|
||||||
|
if !(StoreScope{TenantID: 1, StoreID: 2}).Valid() {
|
||||||
|
t.Fatal("complete scope must be valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireWriteScope(t *testing.T) {
|
||||||
|
if err := requireWriteScope(StoreScope{}); err != ErrStoreScopeRequired {
|
||||||
|
t.Fatalf("empty scope err = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDuplicateSPUNoConstraintNames(t *testing.T) {
|
||||||
|
old := &pgconn.PgError{Code: "23505", ConstraintName: "uq_products_spu_no"}
|
||||||
|
if !isPostgresConstraintError(old, "23505", "uq_products_spu_no") {
|
||||||
|
t.Fatal("old spu unique name must match")
|
||||||
|
}
|
||||||
|
next := &pgconn.PgError{Code: "23505", ConstraintName: "uq_products_store_spu_no"}
|
||||||
|
if !isPostgresConstraintError(next, "23505", "uq_products_store_spu_no") {
|
||||||
|
t.Fatal("store-scoped spu unique name must match")
|
||||||
|
}
|
||||||
|
}
|
||||||
504
internal/server/catalog_master_server.go
Normal file
504
internal/server/catalog_master_server.go
Normal file
@ -0,0 +1,504 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxCatalogMasterNameLength = 100
|
||||||
|
const maxCatalogMasterCodeLength = 64
|
||||||
|
|
||||||
|
func (s *ProductServer) CreateSupplier(ctx context.Context, req *productv1.CreateSupplierRequest) (*productv1.CreateSupplierResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
record, err := supplierFromCreate(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")
|
||||||
|
}
|
||||||
|
record.ID = s.idgen.NextString()
|
||||||
|
record.Scope = scope
|
||||||
|
created, err := s.repo.CreateSupplier(ctx, record)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.CreateSupplierResponse{Supplier: toProtoSupplier(created)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) GetSupplier(ctx context.Context, req *productv1.GetSupplierRequest) (*productv1.GetSupplierResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
value, err := s.repo.GetSupplier(ctx, req.GetSupplierId(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.GetSupplierResponse{Supplier: toProtoSupplier(value)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) ListSuppliers(ctx context.Context, req *productv1.ListSuppliersRequest) (*productv1.ListSuppliersResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
page, size, err := catalogPagination(req.GetPage(), req.GetPageSize())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
var statusValue *int32
|
||||||
|
if req.Status != nil {
|
||||||
|
if err := validateCatalogStatus(*req.Status); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
statusValue = req.Status
|
||||||
|
}
|
||||||
|
values, total, err := s.repo.ListSuppliers(ctx, repository.SupplierListFilter{Query: strings.TrimSpace(req.GetQuery()), Status: statusValue, Page: page, PageSize: size}, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
out := make([]*productv1.Supplier, 0, len(values))
|
||||||
|
for i := range values {
|
||||||
|
out = append(out, toProtoSupplier(&values[i]))
|
||||||
|
}
|
||||||
|
return &productv1.ListSuppliersResponse{Suppliers: out, Page: page, PageSize: size, Total: total, TotalPages: catalogTotalPages(total, size)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) UpdateSupplier(ctx context.Context, req *productv1.UpdateSupplierRequest) (*productv1.UpdateSupplierResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
patch, err := supplierPatch(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
value, err := s.repo.UpdateSupplier(ctx, req.GetSupplierId(), patch, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.UpdateSupplierResponse{Supplier: toProtoSupplier(value)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) UpdateSupplierStatus(ctx context.Context, req *productv1.UpdateSupplierStatusRequest) (*productv1.UpdateSupplierStatusResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
if err := validateCatalogStatus(req.GetStatus()); 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")
|
||||||
|
}
|
||||||
|
value, err := s.repo.UpdateSupplierStatus(ctx, req.GetSupplierId(), req.GetStatus(), req.GetExpectedVersion(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.UpdateSupplierStatusResponse{Supplier: toProtoSupplier(value)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) DeleteSupplier(ctx context.Context, req *productv1.DeleteSupplierRequest) (*productv1.DeleteSupplierResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); 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")
|
||||||
|
}
|
||||||
|
deleted, err := s.repo.DeleteSupplier(ctx, req.GetSupplierId(), req.GetExpectedVersion(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.DeleteSupplierResponse{SupplierId: req.GetSupplierId(), DeletedAt: timeToMillisString(*deleted)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) CreateBrand(ctx context.Context, req *productv1.CreateBrandRequest) (*productv1.CreateBrandResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
record, err := brandFromCreate(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")
|
||||||
|
}
|
||||||
|
record.ID = s.idgen.NextString()
|
||||||
|
record.Scope = scope
|
||||||
|
created, err := s.repo.CreateBrand(ctx, record)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.CreateBrandResponse{Brand: toProtoBrand(created)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) GetBrand(ctx context.Context, req *productv1.GetBrandRequest) (*productv1.GetBrandResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetBrandId(), "brand_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
value, err := s.repo.GetBrand(ctx, req.GetBrandId(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.GetBrandResponse{Brand: toProtoBrand(value)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) ListBrands(ctx context.Context, req *productv1.ListBrandsRequest) (*productv1.ListBrandsResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
page, size, err := catalogPagination(req.GetPage(), req.GetPageSize())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
if req.GetSupplierId() != "" {
|
||||||
|
if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var statusValue *int32
|
||||||
|
if req.Status != nil {
|
||||||
|
if err := validateCatalogStatus(*req.Status); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
statusValue = req.Status
|
||||||
|
}
|
||||||
|
values, total, err := s.repo.ListBrands(ctx, repository.BrandListFilter{Query: strings.TrimSpace(req.GetQuery()), SupplierID: strings.TrimSpace(req.GetSupplierId()), Status: statusValue, Page: page, PageSize: size}, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
out := make([]*productv1.Brand, 0, len(values))
|
||||||
|
for i := range values {
|
||||||
|
out = append(out, toProtoBrand(&values[i]))
|
||||||
|
}
|
||||||
|
return &productv1.ListBrandsResponse{Brands: out, Page: page, PageSize: size, Total: total, TotalPages: catalogTotalPages(total, size)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) UpdateBrand(ctx context.Context, req *productv1.UpdateBrandRequest) (*productv1.UpdateBrandResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetBrandId(), "brand_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
patch, err := brandPatch(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
value, err := s.repo.UpdateBrand(ctx, req.GetBrandId(), patch, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.UpdateBrandResponse{Brand: toProtoBrand(value)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) UpdateBrandStatus(ctx context.Context, req *productv1.UpdateBrandStatusRequest) (*productv1.UpdateBrandStatusResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetBrandId(), "brand_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
if err := validateCatalogStatus(req.GetStatus()); 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")
|
||||||
|
}
|
||||||
|
value, err := s.repo.UpdateBrandStatus(ctx, req.GetBrandId(), req.GetStatus(), req.GetExpectedVersion(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.UpdateBrandStatusResponse{Brand: toProtoBrand(value)}, nil
|
||||||
|
}
|
||||||
|
func (s *ProductServer) DeleteBrand(ctx context.Context, req *productv1.DeleteBrandRequest) (*productv1.DeleteBrandResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetBrandId(), "brand_id"); 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")
|
||||||
|
}
|
||||||
|
deleted, err := s.repo.DeleteBrand(ctx, req.GetBrandId(), req.GetExpectedVersion(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, catalogGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.DeleteBrandResponse{BrandId: req.GetBrandId(), DeletedAt: timeToMillisString(*deleted)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func supplierFromCreate(req *productv1.CreateSupplierRequest) (repository.SupplierRecord, error) {
|
||||||
|
statusValue := int32(1)
|
||||||
|
if req.Status != nil {
|
||||||
|
statusValue = *req.Status
|
||||||
|
}
|
||||||
|
if err := validateCatalogStatus(statusValue); err != nil {
|
||||||
|
return repository.SupplierRecord{}, err
|
||||||
|
}
|
||||||
|
attachments, err := attachmentsFromProto(req.GetAttachments())
|
||||||
|
if err != nil {
|
||||||
|
return repository.SupplierRecord{}, err
|
||||||
|
}
|
||||||
|
return repository.SupplierRecord{Name: catalogName(req.GetName(), "name"), Alias: strings.TrimSpace(req.GetAlias()), SupplierCode: catalogCode(req.GetSupplierCode(), "supplier_code"), Attachments: attachments, ContactName: strings.TrimSpace(req.GetContactName()), ContactPhone: strings.TrimSpace(req.GetContactPhone()), Remark: strings.TrimSpace(req.GetRemark()), Status: statusValue}, validateCatalogMasterFields(catalogName(req.GetName(), "name"), catalogCode(req.GetSupplierCode(), "supplier_code"))
|
||||||
|
}
|
||||||
|
func brandFromCreate(req *productv1.CreateBrandRequest) (repository.BrandRecord, error) {
|
||||||
|
statusValue := int32(1)
|
||||||
|
if req.Status != nil {
|
||||||
|
statusValue = *req.Status
|
||||||
|
}
|
||||||
|
if err := validateCatalogStatus(statusValue); err != nil {
|
||||||
|
return repository.BrandRecord{}, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetSupplierId(), "supplier_id"); err != nil {
|
||||||
|
return repository.BrandRecord{}, err
|
||||||
|
}
|
||||||
|
name, code := catalogName(req.GetName(), "name"), catalogCode(req.GetBrandCode(), "brand_code")
|
||||||
|
if err := validateCatalogMasterFields(name, code); err != nil {
|
||||||
|
return repository.BrandRecord{}, err
|
||||||
|
}
|
||||||
|
return repository.BrandRecord{Name: name, Alias: strings.TrimSpace(req.GetAlias()), BrandCode: code, SupplierID: req.GetSupplierId(), Status: statusValue}, nil
|
||||||
|
}
|
||||||
|
func supplierPatch(req *productv1.UpdateSupplierRequest) (repository.SupplierPatch, error) {
|
||||||
|
if req.GetSupplier() == nil {
|
||||||
|
return repository.SupplierPatch{}, errors.New("supplier is required")
|
||||||
|
}
|
||||||
|
if req.GetExpectedVersion() < 0 {
|
||||||
|
return repository.SupplierPatch{}, errors.New("expected_version must be non-negative")
|
||||||
|
}
|
||||||
|
out := repository.SupplierPatch{ExpectedVersion: req.GetExpectedVersion()}
|
||||||
|
for _, field := range req.GetUpdateMask().GetPaths() {
|
||||||
|
switch field {
|
||||||
|
case "name":
|
||||||
|
v := catalogName(req.GetSupplier().GetName(), "name")
|
||||||
|
if err := validateCatalogName(v); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Name = &v
|
||||||
|
case "alias":
|
||||||
|
v := strings.TrimSpace(req.GetSupplier().GetAlias())
|
||||||
|
out.Alias = &v
|
||||||
|
case "supplier_code":
|
||||||
|
v := catalogCode(req.GetSupplier().GetSupplierCode(), "supplier_code")
|
||||||
|
if err := validateCatalogCode(v); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.SupplierCode = &v
|
||||||
|
case "attachments":
|
||||||
|
v, err := attachmentsFromProto(req.GetSupplier().GetAttachments())
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Attachments = &v
|
||||||
|
case "contact_name":
|
||||||
|
v := strings.TrimSpace(req.GetSupplier().GetContactName())
|
||||||
|
out.ContactName = &v
|
||||||
|
case "contact_phone":
|
||||||
|
v := strings.TrimSpace(req.GetSupplier().GetContactPhone())
|
||||||
|
out.ContactPhone = &v
|
||||||
|
case "remark":
|
||||||
|
v := strings.TrimSpace(req.GetSupplier().GetRemark())
|
||||||
|
out.Remark = &v
|
||||||
|
default:
|
||||||
|
return out, fmt.Errorf("unsupported update_mask path: %s", field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
func brandPatch(req *productv1.UpdateBrandRequest) (repository.BrandPatch, error) {
|
||||||
|
if req.GetBrand() == nil {
|
||||||
|
return repository.BrandPatch{}, errors.New("brand is required")
|
||||||
|
}
|
||||||
|
if req.GetExpectedVersion() < 0 {
|
||||||
|
return repository.BrandPatch{}, errors.New("expected_version must be non-negative")
|
||||||
|
}
|
||||||
|
out := repository.BrandPatch{ExpectedVersion: req.GetExpectedVersion()}
|
||||||
|
for _, field := range req.GetUpdateMask().GetPaths() {
|
||||||
|
switch field {
|
||||||
|
case "name":
|
||||||
|
v := catalogName(req.GetBrand().GetName(), "name")
|
||||||
|
if err := validateCatalogName(v); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Name = &v
|
||||||
|
case "alias":
|
||||||
|
v := strings.TrimSpace(req.GetBrand().GetAlias())
|
||||||
|
out.Alias = &v
|
||||||
|
case "brand_code":
|
||||||
|
v := catalogCode(req.GetBrand().GetBrandCode(), "brand_code")
|
||||||
|
if err := validateCatalogCode(v); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.BrandCode = &v
|
||||||
|
case "supplier_id":
|
||||||
|
v := strings.TrimSpace(req.GetBrand().GetSupplierId())
|
||||||
|
if err := validatePositiveID(v, "supplier_id"); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.SupplierID = &v
|
||||||
|
default:
|
||||||
|
return out, fmt.Errorf("unsupported update_mask path: %s", field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
func attachmentsFromProto(values []*productv1.SupplierAttachment) ([]repository.SupplierAttachmentRecord, error) {
|
||||||
|
out := make([]repository.SupplierAttachmentRecord, 0, len(values))
|
||||||
|
for _, item := range values {
|
||||||
|
if item == nil || strings.TrimSpace(item.GetFileId()) == "" {
|
||||||
|
return nil, errors.New("attachments[].file_id is required")
|
||||||
|
}
|
||||||
|
out = append(out, repository.SupplierAttachmentRecord{FileID: strings.TrimSpace(item.GetFileId()), FileName: strings.TrimSpace(item.GetFileName()), FileType: strings.TrimSpace(item.GetFileType())})
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
func catalogName(value, _ string) string { return strings.TrimSpace(value) }
|
||||||
|
func catalogCode(value, _ string) string { return strings.TrimSpace(value) }
|
||||||
|
func validateCatalogMasterFields(name, code string) error {
|
||||||
|
if err := validateCatalogName(name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return validateCatalogCode(code)
|
||||||
|
}
|
||||||
|
func validateCatalogName(value string) error {
|
||||||
|
if value == "" {
|
||||||
|
return errors.New("name is required")
|
||||||
|
}
|
||||||
|
if len([]rune(value)) > maxCatalogMasterNameLength {
|
||||||
|
return fmt.Errorf("name must be at most %d characters", maxCatalogMasterNameLength)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func validateCatalogCode(value string) error {
|
||||||
|
if value == "" {
|
||||||
|
return errors.New("code is required")
|
||||||
|
}
|
||||||
|
if len([]rune(value)) > maxCatalogMasterCodeLength {
|
||||||
|
return fmt.Errorf("code must be at most %d characters", maxCatalogMasterCodeLength)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func validateCatalogStatus(value int32) error {
|
||||||
|
if value != 0 && value != 1 {
|
||||||
|
return errors.New("status must be 0 or 1")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func catalogPagination(page, size int32) (int32, int32, error) {
|
||||||
|
if page == 0 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if size == 0 {
|
||||||
|
size = defaultPageSize
|
||||||
|
}
|
||||||
|
if page < 1 {
|
||||||
|
return 0, 0, errors.New("page must be positive")
|
||||||
|
}
|
||||||
|
if size < 1 || size > maxPageSize {
|
||||||
|
return 0, 0, fmt.Errorf("page_size must be between 1 and %d", maxPageSize)
|
||||||
|
}
|
||||||
|
return page, size, nil
|
||||||
|
}
|
||||||
|
func catalogTotalPages(total int64, size int32) int32 {
|
||||||
|
if total == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return int32((total + int64(size) - 1) / int64(size))
|
||||||
|
}
|
||||||
|
func toProtoSupplier(value *repository.SupplierRecord) *productv1.Supplier {
|
||||||
|
if value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := &productv1.Supplier{SupplierId: value.ID, Name: value.Name, Alias: value.Alias, SupplierCode: value.SupplierCode, ContactName: value.ContactName, ContactPhone: value.ContactPhone, Remark: value.Remark, Status: value.Status, TenantId: fmt.Sprint(value.Scope.TenantID), StoreId: fmt.Sprint(value.Scope.StoreID), CreatedAt: timeToMillisString(value.CreatedAt), UpdatedAt: timeToMillisString(value.UpdatedAt), Version: value.Version}
|
||||||
|
for _, item := range value.Attachments {
|
||||||
|
out.Attachments = append(out.Attachments, &productv1.SupplierAttachment{FileId: item.FileID, FileName: item.FileName, FileType: item.FileType})
|
||||||
|
}
|
||||||
|
for i := range value.Brands {
|
||||||
|
out.Brands = append(out.Brands, toProtoBrand(&value.Brands[i]))
|
||||||
|
}
|
||||||
|
out.DeletedAt = timePtrToMillisString(value.DeletedAt)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func toProtoBrand(value *repository.BrandRecord) *productv1.Brand {
|
||||||
|
if value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &productv1.Brand{BrandId: value.ID, Name: value.Name, Alias: value.Alias, BrandCode: value.BrandCode, SupplierId: value.SupplierID, Status: value.Status, TenantId: fmt.Sprint(value.Scope.TenantID), StoreId: fmt.Sprint(value.Scope.StoreID), CreatedAt: timeToMillisString(value.CreatedAt), UpdatedAt: timeToMillisString(value.UpdatedAt), DeletedAt: timePtrToMillisString(value.DeletedAt), Version: value.Version, ProductCount: value.ProductCount}
|
||||||
|
}
|
||||||
|
func catalogGRPCError(err error) error {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, repository.ErrSupplierNotFound), errors.Is(err, repository.ErrBrandNotFound):
|
||||||
|
return status.Error(codes.NotFound, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrSupplierVersionConflict), errors.Is(err, repository.ErrBrandVersionConflict):
|
||||||
|
return status.Error(codes.Aborted, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrDuplicateSupplierCode), errors.Is(err, repository.ErrDuplicateBrandCode):
|
||||||
|
return status.Error(codes.AlreadyExists, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrSupplierHasBrands), errors.Is(err, repository.ErrSupplierHasActiveBrands), errors.Is(err, repository.ErrBrandInUse), errors.Is(err, repository.ErrSupplierInactive), errors.Is(err, repository.ErrBrandInactive), errors.Is(err, repository.ErrBrandSupplierMismatch):
|
||||||
|
return status.Error(codes.FailedPrecondition, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrStoreScopeRequired):
|
||||||
|
return status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
default:
|
||||||
|
return status.Error(codes.Internal, "catalog master operation failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -29,3 +29,42 @@ func TestCategoryImageIDsRoundTripThroughExistingProtoField(t *testing.T) {
|
|||||||
t.Fatal("expected non-array image_json to be rejected")
|
t.Fatal("expected non-array image_json to be rejected")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGroupNodeIncludesBrandProductsOnlyForLeafGroups(t *testing.T) {
|
||||||
|
parent := toProtoGroupNode(&repository.CategoryRecord{
|
||||||
|
ID: "1001",
|
||||||
|
Level: 1,
|
||||||
|
IsLeaf: false,
|
||||||
|
})
|
||||||
|
if parent.GetIsLeaf() || parent.GetBrands() != nil {
|
||||||
|
t.Fatalf("parent = %#v, want non-leaf without brands", parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
leaf := toProtoGroupNode(&repository.CategoryRecord{
|
||||||
|
ID: "1002",
|
||||||
|
Level: 1,
|
||||||
|
IsLeaf: true,
|
||||||
|
BrandProducts: []repository.GroupBrandProductRecord{{
|
||||||
|
BrandID: "3001",
|
||||||
|
BrandName: "Brand",
|
||||||
|
Products: []repository.GroupBrandProductItemRecord{{
|
||||||
|
ProductID: "2002",
|
||||||
|
SPUNo: "SPU-2",
|
||||||
|
}, {
|
||||||
|
ProductID: "2001",
|
||||||
|
SPUNo: "SPU-1",
|
||||||
|
}},
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if !leaf.GetIsLeaf() || len(leaf.GetBrands()) != 1 {
|
||||||
|
t.Fatalf("leaf = %#v, want one brand", leaf)
|
||||||
|
}
|
||||||
|
if got := leaf.GetBrands()[0].GetProducts(); len(got) != 2 || got[0].GetProductId() != "2002" || got[0].GetSpuNo() != "SPU-2" || got[1].GetProductId() != "2001" || got[1].GetSpuNo() != "SPU-1" {
|
||||||
|
t.Fatalf("brand products = %#v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
emptyLeaf := toProtoGroupNode(&repository.CategoryRecord{ID: "1003", Level: 2, IsLeaf: true})
|
||||||
|
if got := emptyLeaf.GetBrands(); got == nil || len(got) != 0 {
|
||||||
|
t.Fatalf("empty leaf brands = %#v, want []", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
58
internal/server/category_name_test.go
Normal file
58
internal/server/category_name_test.go
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNormalizeNodeNameCollapsesUnicodeWhitespace(t *testing.T) {
|
||||||
|
name, err := normalizeNodeName(" Summer\t\n Sale ", "name")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("normalizeNodeName: %v", err)
|
||||||
|
}
|
||||||
|
if name != "Summer Sale" {
|
||||||
|
t.Fatalf("normalized name = %q, want %q", name, "Summer Sale")
|
||||||
|
}
|
||||||
|
if normalizedNodeNameKey(name) != normalizedNodeNameKey("summer sale") {
|
||||||
|
t.Fatal("normalized name key must ignore case")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupTreeFromCreateRequestAcceptsChildren(t *testing.T) {
|
||||||
|
group, children, err := groupTreeFromCreateRequest(&productv1.CreateGroupRequest{
|
||||||
|
Name: "Parent group",
|
||||||
|
Children: []*productv1.CreateChildGroup{
|
||||||
|
{Name: "Child group"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("groupTreeFromCreateRequest: %v", err)
|
||||||
|
}
|
||||||
|
if group.Level != 1 || len(children) != 1 || children[0].Level != 2 {
|
||||||
|
t.Fatalf("group = %#v, children = %#v", group, children)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, _, err := groupTreeFromCreateRequest(&productv1.CreateGroupRequest{Name: "Parent", Children: []*productv1.CreateChildGroup{{Name: "same"}, {Name: "same"}}}); err == nil {
|
||||||
|
t.Fatal("expected duplicate child names to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCategoryTreeFromCreateRequestAcceptsNestedChildren(t *testing.T) {
|
||||||
|
root, children, err := categoryTreeFromCreateRequest(&productv1.CreateCategoryTreeRequest{
|
||||||
|
Name: "服饰",
|
||||||
|
Children: []*productv1.CreateChildCategory{{
|
||||||
|
Name: "女装",
|
||||||
|
Children: []*productv1.CreateChildCategory{{
|
||||||
|
Name: "连衣裙",
|
||||||
|
Children: []*productv1.CreateChildCategory{{Name: "长裙"}},
|
||||||
|
}},
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("categoryTreeFromCreateRequest: %v", err)
|
||||||
|
}
|
||||||
|
if root.Level != 1 || len(children) != 1 || len(children[0].Children) != 1 || len(children[0].Children[0].Children) != 1 {
|
||||||
|
t.Fatalf("nested category tree was not preserved: root=%#v children=%#v", root, children)
|
||||||
|
}
|
||||||
|
}
|
||||||
282
internal/server/freight_template_server.go
Normal file
282
internal/server/freight_template_server.go
Normal file
@ -0,0 +1,282 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/freight"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxFreightTemplateNameLength = 64
|
||||||
|
|
||||||
|
func (s *ProductServer) CreateFreightTemplate(ctx context.Context, req *productv1.CreateFreightTemplateRequest) (*productv1.CreateFreightTemplateResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rec, err := freightTemplateFromCreate(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")
|
||||||
|
}
|
||||||
|
rec.ID = s.idgen.NextString()
|
||||||
|
rec.Scope = scope
|
||||||
|
created, err := s.repo.CreateFreightTemplate(ctx, rec)
|
||||||
|
if err != nil {
|
||||||
|
return nil, freightTemplateGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.CreateFreightTemplateResponse{Template: toProtoFreightTemplate(created)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) GetFreightTemplate(ctx context.Context, req *productv1.GetFreightTemplateRequest) (*productv1.GetFreightTemplateResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetTemplateId(), "template_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
value, err := s.repo.GetFreightTemplate(ctx, req.GetTemplateId(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, freightTemplateGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.GetFreightTemplateResponse{Template: toProtoFreightTemplate(value)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) ListFreightTemplates(ctx context.Context, req *productv1.ListFreightTemplatesRequest) (*productv1.ListFreightTemplatesResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
page, size, err := catalogPagination(req.GetPage(), req.GetPageSize())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
var statusValue *int32
|
||||||
|
if req.Status != nil {
|
||||||
|
if *req.Status != 0 && *req.Status != 1 {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "status must be 0 or 1")
|
||||||
|
}
|
||||||
|
statusValue = req.Status
|
||||||
|
}
|
||||||
|
values, total, err := s.repo.ListFreightTemplates(ctx, repository.FreightTemplateListFilter{
|
||||||
|
Keyword: strings.TrimSpace(req.GetKeyword()), ExactMatch: req.GetExactMatch(), Status: statusValue, Page: page, PageSize: size,
|
||||||
|
}, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, freightTemplateGRPCError(err)
|
||||||
|
}
|
||||||
|
out := make([]*productv1.FreightTemplate, 0, len(values))
|
||||||
|
for i := range values {
|
||||||
|
out = append(out, toProtoFreightTemplate(&values[i]))
|
||||||
|
}
|
||||||
|
return &productv1.ListFreightTemplatesResponse{
|
||||||
|
Templates: out, Page: page, PageSize: size, Total: total, TotalPages: catalogTotalPages(total, size),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) UpdateFreightTemplate(ctx context.Context, req *productv1.UpdateFreightTemplateRequest) (*productv1.UpdateFreightTemplateResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetTemplateId(), "template_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
patch, err := freightTemplatePatch(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
updated, err := s.repo.UpdateFreightTemplate(ctx, req.GetTemplateId(), patch, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, freightTemplateGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.UpdateFreightTemplateResponse{Template: toProtoFreightTemplate(updated)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) DeleteFreightTemplate(ctx context.Context, req *productv1.DeleteFreightTemplateRequest) (*productv1.DeleteFreightTemplateResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePositiveID(req.GetTemplateId(), "template_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
deleted, err := s.repo.DeleteFreightTemplate(ctx, req.GetTemplateId(), req.GetExpectedVersion(), scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, freightTemplateGRPCError(err)
|
||||||
|
}
|
||||||
|
deletedAt := ""
|
||||||
|
if deleted.DeletedAt != nil {
|
||||||
|
deletedAt = timeToMillisString(*deleted.DeletedAt)
|
||||||
|
}
|
||||||
|
return &productv1.DeleteFreightTemplateResponse{TemplateId: deleted.ID, DeletedAt: deletedAt}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func freightTemplateFromCreate(req *productv1.CreateFreightTemplateRequest) (repository.FreightTemplateRecord, error) {
|
||||||
|
name := strings.TrimSpace(req.GetName())
|
||||||
|
if name == "" {
|
||||||
|
return repository.FreightTemplateRecord{}, errors.New("name is required")
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(name) > maxFreightTemplateNameLength {
|
||||||
|
return repository.FreightTemplateRecord{}, errors.New("name is too long")
|
||||||
|
}
|
||||||
|
mode := req.GetPricingMode()
|
||||||
|
if mode == 0 {
|
||||||
|
mode = 1
|
||||||
|
}
|
||||||
|
if mode != 1 && mode != 2 {
|
||||||
|
return repository.FreightTemplateRecord{}, errors.New("pricing_mode must be 1 or 2")
|
||||||
|
}
|
||||||
|
var fee *int64
|
||||||
|
if req.DefaultFee != nil {
|
||||||
|
if *req.DefaultFee < 0 {
|
||||||
|
return repository.FreightTemplateRecord{}, errors.New("default_fee must be >= 0")
|
||||||
|
}
|
||||||
|
fee = req.DefaultFee
|
||||||
|
}
|
||||||
|
if mode == 1 && fee == nil {
|
||||||
|
return repository.FreightTemplateRecord{}, errors.New("default_fee is required when pricing_mode is 1")
|
||||||
|
}
|
||||||
|
rules := append([]byte(nil), req.GetRulesJson()...)
|
||||||
|
if mode == 2 {
|
||||||
|
if len(rules) == 0 {
|
||||||
|
return repository.FreightTemplateRecord{}, errors.New("rules_json is required when pricing_mode is 2")
|
||||||
|
}
|
||||||
|
if err := freight.ValidateRulesJSON(rules); err != nil {
|
||||||
|
return repository.FreightTemplateRecord{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st := int32(1)
|
||||||
|
if req.Status != nil {
|
||||||
|
if *req.Status != 0 && *req.Status != 1 {
|
||||||
|
return repository.FreightTemplateRecord{}, errors.New("status must be 0 or 1")
|
||||||
|
}
|
||||||
|
st = *req.Status
|
||||||
|
}
|
||||||
|
return repository.FreightTemplateRecord{
|
||||||
|
Name: name, PricingMode: mode, DefaultFee: fee, RulesJSON: rules, Status: st,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func freightTemplatePatch(req *productv1.UpdateFreightTemplateRequest) (repository.FreightTemplatePatch, error) {
|
||||||
|
paths := make(map[string]struct{})
|
||||||
|
if req.GetUpdateMask() != nil {
|
||||||
|
for _, p := range req.GetUpdateMask().GetPaths() {
|
||||||
|
paths[strings.TrimSpace(p)] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
has := func(name string) bool {
|
||||||
|
if len(paths) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
_, ok := paths[name]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
patch := repository.FreightTemplatePatch{ExpectedVersion: req.GetExpectedVersion()}
|
||||||
|
if has("name") && req.Name != nil {
|
||||||
|
name := strings.TrimSpace(*req.Name)
|
||||||
|
if name == "" {
|
||||||
|
return patch, errors.New("name is required")
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(name) > maxFreightTemplateNameLength {
|
||||||
|
return patch, errors.New("name is too long")
|
||||||
|
}
|
||||||
|
patch.Name = &name
|
||||||
|
}
|
||||||
|
if has("pricing_mode") && req.PricingMode != nil {
|
||||||
|
if *req.PricingMode != 1 && *req.PricingMode != 2 {
|
||||||
|
return patch, errors.New("pricing_mode must be 1 or 2")
|
||||||
|
}
|
||||||
|
patch.PricingMode = req.PricingMode
|
||||||
|
}
|
||||||
|
if has("default_fee") {
|
||||||
|
patch.DefaultFeeSet = true
|
||||||
|
if req.DefaultFee != nil {
|
||||||
|
if *req.DefaultFee < 0 {
|
||||||
|
return patch, errors.New("default_fee must be >= 0")
|
||||||
|
}
|
||||||
|
patch.DefaultFee = req.DefaultFee
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if has("rules_json") && req.RulesJson != nil {
|
||||||
|
b := append([]byte(nil), req.GetRulesJson()...)
|
||||||
|
if err := freight.ValidateRulesJSON(b); err != nil {
|
||||||
|
return patch, err
|
||||||
|
}
|
||||||
|
patch.RulesJSON = &b
|
||||||
|
}
|
||||||
|
if has("status") && req.Status != nil {
|
||||||
|
if *req.Status != 0 && *req.Status != 1 {
|
||||||
|
return patch, errors.New("status must be 0 or 1")
|
||||||
|
}
|
||||||
|
patch.Status = req.Status
|
||||||
|
}
|
||||||
|
if patch.PricingMode != nil && *patch.PricingMode == 2 && patch.RulesJSON == nil {
|
||||||
|
return patch, errors.New("rules_json is required when pricing_mode is 2")
|
||||||
|
}
|
||||||
|
return patch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func toProtoFreightTemplate(rec *repository.FreightTemplateRecord) *productv1.FreightTemplate {
|
||||||
|
if rec == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := &productv1.FreightTemplate{
|
||||||
|
TemplateId: rec.ID,
|
||||||
|
Name: rec.Name,
|
||||||
|
PricingMode: rec.PricingMode,
|
||||||
|
DefaultFee: rec.DefaultFee,
|
||||||
|
RulesJson: append([]byte(nil), rec.RulesJSON...),
|
||||||
|
Status: rec.Status,
|
||||||
|
TenantId: fmt.Sprint(rec.Scope.TenantID),
|
||||||
|
StoreId: fmt.Sprint(rec.Scope.StoreID),
|
||||||
|
CreatedAt: timeToMillisString(rec.CreatedAt),
|
||||||
|
UpdatedAt: timeToMillisString(rec.UpdatedAt),
|
||||||
|
Version: rec.Version,
|
||||||
|
}
|
||||||
|
if rec.DeletedAt != nil {
|
||||||
|
v := timeToMillisString(*rec.DeletedAt)
|
||||||
|
out.DeletedAt = &v
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func freightTemplateGRPCError(err error) error {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, repository.ErrFreightTemplateNotFound):
|
||||||
|
return status.Error(codes.NotFound, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrFreightTemplateVersionConflict):
|
||||||
|
return status.Error(codes.Aborted, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrFreightTemplateInUse):
|
||||||
|
return status.Error(codes.FailedPrecondition, err.Error())
|
||||||
|
case errors.Is(err, repository.ErrFreightTemplateNameExists):
|
||||||
|
return status.Error(codes.AlreadyExists, err.Error())
|
||||||
|
default:
|
||||||
|
return status.Errorf(codes.Internal, "%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
17
internal/server/freight_template_server_test.go
Normal file
17
internal/server/freight_template_server_test.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFreightTemplateNameConflictMapsToAlreadyExists(t *testing.T) {
|
||||||
|
err := freightTemplateGRPCError(repository.ErrFreightTemplateNameExists)
|
||||||
|
if status.Code(err) != codes.AlreadyExists {
|
||||||
|
t.Fatalf("code = %v, want %v", status.Code(err), codes.AlreadyExists)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -10,10 +10,10 @@ import (
|
|||||||
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGetProductBySkuRequiresID(t *testing.T) {
|
func TestGetProductBySkuRequiresIDWithoutStoreIsFailedPrecondition(t *testing.T) {
|
||||||
s := NewProductServer(nil, nil, nil, nil)
|
s := NewProductServer(nil, nil, nil, nil)
|
||||||
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{})
|
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{})
|
||||||
if status.Code(err) != codes.InvalidArgument {
|
if status.Code(err) != codes.FailedPrecondition {
|
||||||
t.Fatalf("err = %v", err)
|
t.Fatalf("err = %v, want FailedPrecondition", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
42
internal/server/html_sanitize.go
Normal file
42
internal/server/html_sanitize.go
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
reScriptTag = regexp.MustCompile(`(?is)<script\b[^>]*>.*?</script>`)
|
||||||
|
reIFrameTag = regexp.MustCompile(`(?is)<iframe\b[^>]*>.*?</iframe>`)
|
||||||
|
reObjectTag = regexp.MustCompile(`(?is)<object\b[^>]*>.*?</object>`)
|
||||||
|
reEmbedTag = regexp.MustCompile(`(?is)<embed\b[^>]*>.*?</embed>`)
|
||||||
|
reEventAttr = regexp.MustCompile(`(?i)\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)`)
|
||||||
|
reJSURL = regexp.MustCompile(`(?i)(href|src)\s*=\s*("|')\s*javascript:[^"']*("|')`)
|
||||||
|
reDataJSURL = regexp.MustCompile(`(?i)(href|src)\s*=\s*("|')\s*data:text/html[^"']*("|')`)
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxDetailHTMLBytes = 512 * 1024
|
||||||
|
|
||||||
|
func sanitizeDetailHTML(raw string) (string, error) {
|
||||||
|
if raw == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
if len(raw) > maxDetailHTMLBytes {
|
||||||
|
return "", errDetailHTMLTooLarge
|
||||||
|
}
|
||||||
|
out := raw
|
||||||
|
out = reScriptTag.ReplaceAllString(out, "")
|
||||||
|
out = reIFrameTag.ReplaceAllString(out, "")
|
||||||
|
out = reObjectTag.ReplaceAllString(out, "")
|
||||||
|
out = reEmbedTag.ReplaceAllString(out, "")
|
||||||
|
out = reEventAttr.ReplaceAllString(out, "")
|
||||||
|
out = reJSURL.ReplaceAllString(out, `$1=""`)
|
||||||
|
out = reDataJSURL.ReplaceAllString(out, `$1=""`)
|
||||||
|
return strings.TrimSpace(out), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type detailHTMLError string
|
||||||
|
|
||||||
|
func (e detailHTMLError) Error() string { return string(e) }
|
||||||
|
|
||||||
|
const errDetailHTMLTooLarge = detailHTMLError("detail_html exceeds maximum size")
|
||||||
34
internal/server/list_product_skus_test.go
Normal file
34
internal/server/list_product_skus_test.go
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
|
||||||
|
commonv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/common/v1"
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestListProductSKUsRequiresStoreContext(t *testing.T) {
|
||||||
|
s := NewProductServer(nil, nil, nil, nil)
|
||||||
|
_, err := s.ListProductSKUs(context.Background(), &productv1.ListProductSKUsRequest{})
|
||||||
|
if status.Code(err) != codes.FailedPrecondition {
|
||||||
|
t.Fatalf("err = %v, want FailedPrecondition", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListProductSKUsRequiresPositiveProductID(t *testing.T) {
|
||||||
|
s := NewProductServer(nil, nil, nil, nil)
|
||||||
|
_, err := s.ListProductSKUs(context.Background(), &productv1.ListProductSKUsRequest{
|
||||||
|
ProductId: "invalid",
|
||||||
|
StoreContext: &commonv1.StoreContext{
|
||||||
|
TenantId: "10",
|
||||||
|
StoreId: "20",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if status.Code(err) != codes.InvalidArgument {
|
||||||
|
t.Fatalf("err = %v, want InvalidArgument", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
64
internal/server/list_products_filter_test.go
Normal file
64
internal/server/list_products_filter_test.go
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductListFilterFromRequestNormalizesImageFilters(t *testing.T) {
|
||||||
|
priceMin := int64(0)
|
||||||
|
priceMax := int64(1999)
|
||||||
|
productStatus := productv1.ProductStatus_PRODUCT_STATUS_INVENTORY
|
||||||
|
filter, err := productListFilterFromRequest(&productv1.ListProductsRequest{
|
||||||
|
TitleKeyword: " coffee ",
|
||||||
|
CategoryId: " 11111 ",
|
||||||
|
PriceMin: &priceMin,
|
||||||
|
PriceMax: &priceMax,
|
||||||
|
Status: &productStatus,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("productListFilterFromRequest() error = %v", err)
|
||||||
|
}
|
||||||
|
if filter.TitleKeyword != "coffee" {
|
||||||
|
t.Fatalf("TitleKeyword = %q, want coffee", filter.TitleKeyword)
|
||||||
|
}
|
||||||
|
if filter.ProductCategoryID != "11111" {
|
||||||
|
t.Fatalf("ProductCategoryID = %q, want 11111", filter.ProductCategoryID)
|
||||||
|
}
|
||||||
|
if filter.PriceMin == nil || *filter.PriceMin != 0 {
|
||||||
|
t.Fatalf("PriceMin = %v, want explicit zero", filter.PriceMin)
|
||||||
|
}
|
||||||
|
if filter.Status == nil || *filter.Status != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY {
|
||||||
|
t.Fatalf("Status = %v, want inventory", filter.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductListFilterFromRequestRejectsInvalidStatus(t *testing.T) {
|
||||||
|
invalidStatus := productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED
|
||||||
|
_, err := productListFilterFromRequest(&productv1.ListProductsRequest{Status: &invalidStatus})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("productListFilterFromRequest() error = nil, want invalid status")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductListFilterFromRequestRejectsInvalidCategoryID(t *testing.T) {
|
||||||
|
_, err := productListFilterFromRequest(&productv1.ListProductsRequest{
|
||||||
|
CategoryId: "not-a-id",
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("productListFilterFromRequest() error = nil, want invalid category_id")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductListFilterFromRequestRejectsInvalidRanges(t *testing.T) {
|
||||||
|
minimum := int64(2)
|
||||||
|
maximum := int64(1)
|
||||||
|
_, err := productListFilterFromRequest(&productv1.ListProductsRequest{
|
||||||
|
SoldQuantityMin: &minimum,
|
||||||
|
SoldQuantityMax: &maximum,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("productListFilterFromRequest() error = nil, want invalid range")
|
||||||
|
}
|
||||||
|
}
|
||||||
177
internal/server/product_batch_server.go
Normal file
177
internal/server/product_batch_server.go
Normal file
@ -0,0 +1,177 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BatchUpdateProductStatus changes lifecycle status for multiple products.
|
||||||
|
func (s *ProductServer) BatchUpdateProductStatus(ctx context.Context, req *productv1.BatchUpdateProductStatusRequest) (*productv1.BatchUpdateProductStatusResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
productIDs, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
next := req.GetStatus()
|
||||||
|
if next == productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "status is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.status", trace.WithAttributes(
|
||||||
|
attribute.Int("product.count", len(productIDs)),
|
||||||
|
attribute.Int("product.status", int(next)),
|
||||||
|
))
|
||||||
|
defer dbSpan.End()
|
||||||
|
|
||||||
|
updated, err := s.repo.BatchUpdateProductStatus(dbCtx, productIDs, next, scope)
|
||||||
|
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.BatchUpdateProductStatusResponse{UpdatedCount: updated}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchDeleteProducts soft-deletes multiple products in one store.
|
||||||
|
func (s *ProductServer) BatchDeleteProducts(ctx context.Context, req *productv1.BatchDeleteProductsRequest) (*productv1.BatchDeleteProductsResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
productIDs, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.delete", trace.WithAttributes(
|
||||||
|
attribute.Int("product.count", len(productIDs)),
|
||||||
|
))
|
||||||
|
defer dbSpan.End()
|
||||||
|
|
||||||
|
if err := s.repo.BatchDeleteProducts(dbCtx, productIDs, scope); err != nil {
|
||||||
|
dbSpan.RecordError(err)
|
||||||
|
dbSpan.SetStatus(otelcodes.Error, err.Error())
|
||||||
|
if errors.Is(err, repository.ErrProductNotFound) {
|
||||||
|
return nil, status.Error(codes.NotFound, "product not found")
|
||||||
|
}
|
||||||
|
s.observer.Logger(ctx).Error("batch delete products failed", zap.Strings("product_ids", productIDs), zap.Error(err))
|
||||||
|
return nil, status.Errorf(codes.Internal, "batch delete products: %v", err)
|
||||||
|
}
|
||||||
|
return &productv1.BatchDeleteProductsResponse{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BatchUpdateProductPrices sets one absolute price on all active SKUs of each product.
|
||||||
|
func (s *ProductServer) BatchUpdateProductPrices(ctx context.Context, req *productv1.BatchUpdateProductPricesRequest) (*productv1.BatchUpdateProductPricesResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
productIDs, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
if req.GetPrice() <= 0 {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "price must be greater than 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.price", trace.WithAttributes(
|
||||||
|
attribute.Int("product.count", len(productIDs)),
|
||||||
|
attribute.Int64("product.price", req.GetPrice()),
|
||||||
|
))
|
||||||
|
defer dbSpan.End()
|
||||||
|
|
||||||
|
result, err := s.repo.BatchUpdateProductPrices(dbCtx, productIDs, req.GetPrice(), scope)
|
||||||
|
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.ErrNoActiveSKU):
|
||||||
|
return nil, status.Error(codes.FailedPrecondition, err.Error())
|
||||||
|
default:
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &productv1.BatchUpdateProductPricesResponse{
|
||||||
|
UpdatedProductCount: result.UpdatedProductCount,
|
||||||
|
UpdatedSkuCount: result.UpdatedSKUCount,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplaceProductsGroup atomically replaces group bindings for multiple products.
|
||||||
|
func (s *ProductServer) ReplaceProductsGroup(ctx context.Context, req *productv1.ReplaceProductsGroupRequest) (*productv1.ReplaceProductsGroupResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if s.idgen == nil {
|
||||||
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||||
|
}
|
||||||
|
productIDs, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
groupID := req.GetGroupId()
|
||||||
|
if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
bindingIDs := make([]string, len(productIDs))
|
||||||
|
for i := range productIDs {
|
||||||
|
bindingIDs[i] = s.idgen.NextString()
|
||||||
|
}
|
||||||
|
|
||||||
|
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.batch.replace_group", trace.WithAttributes(
|
||||||
|
attribute.String("group.id", groupID),
|
||||||
|
attribute.Int("product.count", len(productIDs)),
|
||||||
|
))
|
||||||
|
defer dbSpan.End()
|
||||||
|
|
||||||
|
updated, err := s.repo.ReplaceProductsGroup(dbCtx, productIDs, groupID, bindingIDs, scope)
|
||||||
|
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, "group not found")
|
||||||
|
case errors.Is(err, repository.ErrProductNotFound):
|
||||||
|
return nil, status.Error(codes.NotFound, "product not found")
|
||||||
|
default:
|
||||||
|
s.observer.Logger(ctx).Error("replace products group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err))
|
||||||
|
return nil, status.Errorf(codes.Internal, "replace products group: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &productv1.ReplaceProductsGroupResponse{UpdatedCount: updated}, nil
|
||||||
|
}
|
||||||
46
internal/server/product_category_ids_test.go
Normal file
46
internal/server/product_category_ids_test.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductCategoryIDsFlowThroughCreateUpdateAndResponse(t *testing.T) {
|
||||||
|
request := &productv1.CreateProductRequest{
|
||||||
|
SpuNo: "SPU-category-ids",
|
||||||
|
Title: "Product",
|
||||||
|
Status: productv1.ProductStatus_PRODUCT_STATUS_INVENTORY,
|
||||||
|
ProductCategoryIds: []string{"9001", "9002"},
|
||||||
|
}
|
||||||
|
product, _, err := productFromCreateRequest(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("productFromCreateRequest() error = %v", err)
|
||||||
|
}
|
||||||
|
if want := []string{"9001", "9002"}; !reflect.DeepEqual(product.ProductCategoryIDs, want) {
|
||||||
|
t.Fatalf("create product category ids = %v, want %v", product.ProductCategoryIDs, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
merged, err := mergeProductUpdate(&product, &productv1.ProductUpdate{
|
||||||
|
ProductCategoryIds: []string{"9002", "9003"},
|
||||||
|
}, []string{"product_category_ids"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("mergeProductUpdate() error = %v", err)
|
||||||
|
}
|
||||||
|
if want := []string{"9002", "9003"}; !reflect.DeepEqual(merged.ProductCategoryIDs, want) {
|
||||||
|
t.Fatalf("updated product category ids = %v, want %v", merged.ProductCategoryIDs, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := toProtoProduct(&repository.ProductRecord{ProductCategoryIDs: merged.ProductCategoryIDs}, nil)
|
||||||
|
if want := []string{"9002", "9003"}; !reflect.DeepEqual(response.GetProductCategoryIds(), want) {
|
||||||
|
t.Fatalf("response product category ids = %v, want %v", response.GetProductCategoryIds(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeProductCategoryIDsRejectsDuplicate(t *testing.T) {
|
||||||
|
if _, err := normalizeProductCategoryIDs([]string{"9001", "9001"}); err == nil {
|
||||||
|
t.Fatal("normalizeProductCategoryIDs() accepted duplicate ids")
|
||||||
|
}
|
||||||
|
}
|
||||||
94
internal/server/product_category_platform_test.go
Normal file
94
internal/server/product_category_platform_test.go
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductCategoryFromCreateKeepsPlatformIdentifiers(t *testing.T) {
|
||||||
|
root, err := (&ProductServer{}).productCategoryFromCreate(&productv1.CreateProductCategoryInput{
|
||||||
|
Name: "root",
|
||||||
|
RuleId: "1004",
|
||||||
|
Status: 1,
|
||||||
|
PlatformCategoryId: 100,
|
||||||
|
PlatformParentCategoryId: 0,
|
||||||
|
HasChildren: true,
|
||||||
|
Children: []*productv1.CreateProductCategoryInput{{
|
||||||
|
Name: "child",
|
||||||
|
RuleId: "10040001",
|
||||||
|
Status: 1,
|
||||||
|
PlatformCategoryId: 101,
|
||||||
|
PlatformParentCategoryId: 100,
|
||||||
|
}},
|
||||||
|
}, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if root.PlatformCategoryID != 100 || root.PlatformParentCategoryID != 0 || root.Children[0].PlatformCategoryID != 101 || root.Children[0].PlatformParentCategoryID != 100 {
|
||||||
|
t.Fatalf("platform identifiers were not preserved: %+v", root)
|
||||||
|
}
|
||||||
|
response := toProtoProductCategory(root)
|
||||||
|
if response.GetPlatformCategoryId() != 100 || response.GetPlatformParentCategoryId() != 0 || response.GetChildren()[0].GetPlatformCategoryId() != 101 || response.GetChildren()[0].GetPlatformParentCategoryId() != 100 {
|
||||||
|
t.Fatalf("response platform identifiers were not preserved: %+v", response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToProtoProductCategoryIncludesRootPath(t *testing.T) {
|
||||||
|
rootID := "1001"
|
||||||
|
value := &repository.ProductCategoryRecord{
|
||||||
|
ID: "3003", Name: "连衣裙", Level: 3, ParentID: "2002",
|
||||||
|
Path: []repository.ProductCategoryPathNodeRecord{{
|
||||||
|
ID: "1001", Name: "服饰", Level: 1,
|
||||||
|
}, {
|
||||||
|
ID: "2002", Name: "女装", Level: 2, ParentID: &rootID,
|
||||||
|
}, {
|
||||||
|
ID: "3003", Name: "连衣裙", Level: 3, ParentID: stringPtr("2002"),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
response := toProtoProductCategory(value)
|
||||||
|
if len(response.GetPath()) != 3 || response.GetPath()[0].GetParentCategoryId() != "" || response.GetPath()[2].GetProductCategoryId() != "3003" {
|
||||||
|
t.Fatalf("category path = %#v", response.GetPath())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToProtoProductIncludesStandardCategoryPath(t *testing.T) {
|
||||||
|
product := toProtoProduct(&repository.ProductRecord{
|
||||||
|
ID: "9001",
|
||||||
|
ProductCategories: []repository.ProductCategorySummaryRecord{{
|
||||||
|
ID: "3003", Name: "连衣裙", Level: 3, ParentID: stringPtr("2002"), ParentName: "女装",
|
||||||
|
Path: []repository.ProductCategoryPathNodeRecord{{
|
||||||
|
ID: "1001", Name: "服饰", Level: 1,
|
||||||
|
}, {
|
||||||
|
ID: "3003", Name: "连衣裙", Level: 3, ParentID: stringPtr("2002"),
|
||||||
|
}},
|
||||||
|
}},
|
||||||
|
}, nil)
|
||||||
|
if len(product.GetProductCategories()) != 1 || len(product.GetProductCategories()[0].GetPath()) != 2 {
|
||||||
|
t.Fatalf("product categories = %#v", product.GetProductCategories())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stringPtr(value string) *string { return &value }
|
||||||
|
|
||||||
|
func TestProductCategoryFromCreateRejectsMismatchedPlatformParent(t *testing.T) {
|
||||||
|
_, err := (&ProductServer{}).productCategoryFromCreate(&productv1.CreateProductCategoryInput{
|
||||||
|
Name: "root",
|
||||||
|
RuleId: "1004",
|
||||||
|
Status: 1,
|
||||||
|
PlatformCategoryId: 100,
|
||||||
|
PlatformParentCategoryId: 0,
|
||||||
|
HasChildren: true,
|
||||||
|
Children: []*productv1.CreateProductCategoryInput{{
|
||||||
|
Name: "child",
|
||||||
|
RuleId: "10040001",
|
||||||
|
Status: 1,
|
||||||
|
PlatformCategoryId: 101,
|
||||||
|
PlatformParentCategoryId: 999,
|
||||||
|
}},
|
||||||
|
}, true)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected mismatched platform parent to be rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
289
internal/server/product_category_server.go
Normal file
289
internal/server/product_category_server.go
Normal file
@ -0,0 +1,289 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Taxonomy nodes are global. StoreContext is used only when binding products.
|
||||||
|
func (s *ProductServer) CreateProductCategory(ctx context.Context, req *productv1.CreateProductCategoryRequest) (*productv1.CreateProductCategoryResponse, error) {
|
||||||
|
if req == nil || req.GetProductCategory() == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "product_category is required")
|
||||||
|
}
|
||||||
|
if s.idgen == nil {
|
||||||
|
return nil, status.Error(codes.Internal, "id generator is not configured")
|
||||||
|
}
|
||||||
|
root, err := s.productCategoryFromCreate(req.GetProductCategory(), true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
if err := assignProductCategoryIDs(root, s); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
created, err := s.repo.CreateProductCategory(ctx, root)
|
||||||
|
if err != nil {
|
||||||
|
return nil, productCategoryGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.CreateProductCategoryResponse{ProductCategory: toProtoProductCategory(created)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) GetProductCategory(ctx context.Context, req *productv1.GetProductCategoryRequest) (*productv1.GetProductCategoryResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
value, err := s.repo.GetProductCategory(ctx, req.GetProductCategoryId())
|
||||||
|
if err != nil {
|
||||||
|
return nil, productCategoryGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.GetProductCategoryResponse{ProductCategory: toProtoProductCategory(value)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) ListProductCategories(ctx context.Context, req *productv1.ListProductCategoriesRequest) (*productv1.ListProductCategoriesResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
id := strings.TrimSpace(req.GetProductCategoryId())
|
||||||
|
if id != "" {
|
||||||
|
if _, err := parsePositiveID(id, "product_category_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if req.PlatformCategoryId != nil && req.GetPlatformCategoryId() <= 0 {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "platform_category_id must be positive")
|
||||||
|
}
|
||||||
|
values, err := s.repo.ListProductCategories(ctx, repository.ProductCategoryListFilter{
|
||||||
|
ProductCategoryID: id,
|
||||||
|
PlatformCategoryID: req.PlatformCategoryId,
|
||||||
|
Name: strings.TrimSpace(req.GetName()),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, productCategoryGRPCError(err)
|
||||||
|
}
|
||||||
|
out := make([]*productv1.ProductCategory, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
out = append(out, toProtoProductCategory(value))
|
||||||
|
}
|
||||||
|
return &productv1.ListProductCategoriesResponse{ProductCategories: out}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) UpdateProductCategory(ctx context.Context, req *productv1.UpdateProductCategoryRequest) (*productv1.UpdateProductCategoryResponse, error) {
|
||||||
|
if req == nil || req.GetProductCategory() == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "product_category is required")
|
||||||
|
}
|
||||||
|
if req.GetProductCategoryId() != req.GetProductCategory().GetProductCategoryId() {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "product_category_id must equal the path ID")
|
||||||
|
}
|
||||||
|
patch, err := productCategoryPatchFromProto(req.GetProductCategory())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
value, err := s.repo.UpdateProductCategory(ctx, req.GetProductCategoryId(), patch)
|
||||||
|
if err != nil {
|
||||||
|
return nil, productCategoryGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.UpdateProductCategoryResponse{ProductCategory: toProtoProductCategory(value)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) DeleteProductCategory(ctx context.Context, req *productv1.DeleteProductCategoryRequest) (*productv1.DeleteProductCategoryResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
if _, err := parsePositiveID(req.GetProductCategoryId(), "product_category_id"); err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
result, err := s.repo.DeleteProductCategory(ctx, req.GetProductCategoryId(), req.GetExpectedVersion())
|
||||||
|
if err != nil {
|
||||||
|
return nil, productCategoryGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.DeleteProductCategoryResponse{DeletedProductCategoryIds: result.CategoryIDs, DeletedCategoryCount: result.CategoryCount, UnboundBindingCount: result.BindingCount, UnboundProductCount: result.ProductCount, DeletedAt: result.DeletedAt.Format("2006-01-02T15:04:05Z07:00")}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) BindProductsToProductCategory(ctx context.Context, req *productv1.BindProductsToProductCategoryRequest) (*productv1.BindProductsToProductCategoryResponse, 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")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ids, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
bindingIDs := make([]string, len(ids))
|
||||||
|
for i := range ids {
|
||||||
|
bindingIDs[i] = s.idgen.NextString()
|
||||||
|
}
|
||||||
|
bound, already, err := s.repo.BindProductsToProductCategory(ctx, req.GetProductCategoryId(), bindingIDs, ids, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, productCategoryGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.BindProductsToProductCategoryResponse{BoundCount: bound, AlreadyBoundCount: already}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) UnbindProductsFromProductCategory(ctx context.Context, req *productv1.UnbindProductsFromProductCategoryRequest) (*productv1.UnbindProductsFromProductCategoryResponse, error) {
|
||||||
|
if req == nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "request is required")
|
||||||
|
}
|
||||||
|
scope, err := requireStoreScope(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ids, err := normalizeGroupProductIDs(req.GetProductIds())
|
||||||
|
if err != nil {
|
||||||
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
count, err := s.repo.UnbindProductsFromProductCategory(ctx, req.GetProductCategoryId(), ids, scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, productCategoryGRPCError(err)
|
||||||
|
}
|
||||||
|
return &productv1.UnbindProductsFromProductCategoryResponse{UnboundCount: count}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ProductServer) productCategoryFromCreate(input *productv1.CreateProductCategoryInput, root bool) (*repository.ProductCategoryRecord, error) {
|
||||||
|
if input == nil {
|
||||||
|
return nil, errors.New("product category is required")
|
||||||
|
}
|
||||||
|
name, ruleID := strings.TrimSpace(input.GetName()), strings.TrimSpace(input.GetRuleId())
|
||||||
|
if name == "" || len(name) > 100 {
|
||||||
|
return nil, errors.New("name must contain between 1 and 100 characters")
|
||||||
|
}
|
||||||
|
if ruleID == "" || len(ruleID) > 64 {
|
||||||
|
return nil, errors.New("rule_id must contain between 1 and 64 characters")
|
||||||
|
}
|
||||||
|
if input.GetStatus() != 0 && input.GetStatus() != 1 {
|
||||||
|
return nil, errors.New("status must be 0 or 1")
|
||||||
|
}
|
||||||
|
if len(input.GetCertStatusMsg()) > 500 {
|
||||||
|
return nil, errors.New("cert_status_msg must contain at most 500 characters")
|
||||||
|
}
|
||||||
|
if input.GetPlatformCategoryId() <= 0 {
|
||||||
|
return nil, errors.New("platform_category_id must be positive")
|
||||||
|
}
|
||||||
|
if input.GetPlatformParentCategoryId() < 0 {
|
||||||
|
return nil, errors.New("platform_parent_category_id must be non-negative")
|
||||||
|
}
|
||||||
|
if root && input.ParentId == nil && input.GetPlatformParentCategoryId() != 0 {
|
||||||
|
return nil, errors.New("root platform_parent_category_id must be 0")
|
||||||
|
}
|
||||||
|
if !root && input.ParentId != nil {
|
||||||
|
return nil, errors.New("children must not specify parent_id")
|
||||||
|
}
|
||||||
|
if len(input.GetChildren()) > 0 && !input.GetHasChildren() {
|
||||||
|
return nil, errors.New("has_children must be true when children are supplied")
|
||||||
|
}
|
||||||
|
value := &repository.ProductCategoryRecord{Name: name, RuleID: ruleID, Priority: input.GetPriority(), Status: input.GetStatus(), CategoryType: input.GetCategoryType(), ChannelList: input.GetChannelList(), HasChildren: input.GetHasChildren(), HasPropRequired: input.GetHasPropRequired(), Extra: input.GetExtra(), CertStatusCode: input.GetCertStatusCode(), CertStatusPass: input.GetCertStatusPass(), CertStatusMsg: input.GetCertStatusMsg(), PlatformCategoryID: input.GetPlatformCategoryId(), PlatformParentCategoryID: input.GetPlatformParentCategoryId()}
|
||||||
|
if input.ParentId != nil {
|
||||||
|
value.ParentID = strings.TrimSpace(input.GetParentId())
|
||||||
|
}
|
||||||
|
for _, child := range input.GetChildren() {
|
||||||
|
item, err := s.productCategoryFromCreate(child, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if item.PlatformParentCategoryID != value.PlatformCategoryID {
|
||||||
|
return nil, errors.New("child platform_parent_category_id must equal its parent's platform_category_id")
|
||||||
|
}
|
||||||
|
value.Children = append(value.Children, item)
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func productCategoryPatchFromProto(input *productv1.ProductCategoryPatch) (*repository.ProductCategoryPatch, error) {
|
||||||
|
if input == nil || strings.TrimSpace(input.GetProductCategoryId()) == "" {
|
||||||
|
return nil, errors.New("product_category_id is required")
|
||||||
|
}
|
||||||
|
if input.GetExpectedVersion() < 0 {
|
||||||
|
return nil, errors.New("expected_version must be non-negative")
|
||||||
|
}
|
||||||
|
if input.Name != nil && (strings.TrimSpace(input.GetName()) == "" || len(strings.TrimSpace(input.GetName())) > 100) {
|
||||||
|
return nil, errors.New("name must contain between 1 and 100 characters")
|
||||||
|
}
|
||||||
|
if input.RuleId != nil && (strings.TrimSpace(input.GetRuleId()) == "" || len(strings.TrimSpace(input.GetRuleId())) > 64) {
|
||||||
|
return nil, errors.New("rule_id must contain between 1 and 64 characters")
|
||||||
|
}
|
||||||
|
if input.Status != nil && input.GetStatus() != 0 && input.GetStatus() != 1 {
|
||||||
|
return nil, errors.New("status must be 0 or 1")
|
||||||
|
}
|
||||||
|
if input.CertStatusMsg != nil && len(input.GetCertStatusMsg()) > 500 {
|
||||||
|
return nil, errors.New("cert_status_msg must contain at most 500 characters")
|
||||||
|
}
|
||||||
|
patch := &repository.ProductCategoryPatch{ID: strings.TrimSpace(input.GetProductCategoryId()), ExpectedVersion: input.GetExpectedVersion(), Name: input.Name, Priority: input.Priority, RuleID: input.RuleId, Status: input.Status, CategoryType: input.CategoryType, HasChildren: input.HasChildren, HasPropRequired: input.HasPropRequired, Extra: input.Extra, CertStatusCode: input.CertStatusCode, CertStatusPass: input.CertStatusPass, CertStatusMsg: input.CertStatusMsg}
|
||||||
|
if input.ChannelList != nil {
|
||||||
|
patch.ChannelList = &input.ChannelList
|
||||||
|
}
|
||||||
|
for _, child := range input.GetChildren() {
|
||||||
|
item, err := productCategoryPatchFromProto(child)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
patch.Children = append(patch.Children, item)
|
||||||
|
}
|
||||||
|
return patch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func assignProductCategoryIDs(node *repository.ProductCategoryRecord, s *ProductServer) error {
|
||||||
|
if node == nil {
|
||||||
|
return errors.New("product category is required")
|
||||||
|
}
|
||||||
|
node.ID = s.idgen.NextString()
|
||||||
|
for _, child := range node.Children {
|
||||||
|
if err := assignProductCategoryIDs(child, s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func toProtoProductCategory(value *repository.ProductCategoryRecord) *productv1.ProductCategory {
|
||||||
|
if value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := &productv1.ProductCategory{ProductCategoryId: value.ID, Name: value.Name, Level: value.Level, Priority: value.Priority, RuleId: value.RuleID, Status: value.Status, CategoryType: value.CategoryType, ChannelList: value.ChannelList, HasChildren: value.HasChildren, HasPropRequired: value.HasPropRequired, Extra: value.Extra, CertStatusCode: value.CertStatusCode, CertStatusPass: value.CertStatusPass, CertStatusMsg: value.CertStatusMsg, PlatformCategoryId: value.PlatformCategoryID, PlatformParentCategoryId: value.PlatformParentCategoryID, Version: value.Version, CreatedAt: value.CreatedAt.Format("2006-01-02T15:04:05Z07:00"), UpdatedAt: value.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"), ProductCount: value.ProductCount}
|
||||||
|
if value.ParentID != "" {
|
||||||
|
out.ParentId = &value.ParentID
|
||||||
|
}
|
||||||
|
if value.DeletedAt != nil {
|
||||||
|
formatted := value.DeletedAt.Format("2006-01-02T15:04:05Z07:00")
|
||||||
|
out.DeletedAt = &formatted
|
||||||
|
}
|
||||||
|
for _, child := range value.Children {
|
||||||
|
out.Children = append(out.Children, toProtoProductCategory(child))
|
||||||
|
}
|
||||||
|
for _, node := range value.Path {
|
||||||
|
out.Path = append(out.Path, &productv1.ProductCategoryPathNode{
|
||||||
|
ProductCategoryId: node.ID,
|
||||||
|
Name: node.Name,
|
||||||
|
Level: node.Level,
|
||||||
|
ParentCategoryId: node.ParentID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func productCategoryGRPCError(err error) error {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, repository.ErrProductCategoryNotFound):
|
||||||
|
return status.Error(codes.NotFound, "product category not found")
|
||||||
|
case errors.Is(err, repository.ErrProductCategoryVersionConflict):
|
||||||
|
return status.Error(codes.Aborted, "product category version conflict")
|
||||||
|
case errors.Is(err, repository.ErrDuplicateProductCategory):
|
||||||
|
return status.Error(codes.AlreadyExists, "duplicate product category name")
|
||||||
|
case errors.Is(err, repository.ErrDuplicatePlatformCategory):
|
||||||
|
return status.Error(codes.AlreadyExists, "duplicate platform category id")
|
||||||
|
default:
|
||||||
|
return status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
42
internal/server/product_codes_test.go
Normal file
42
internal/server/product_codes_test.go
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductFromCreateRequestAllowsEmptySPUNoAndRepeatedSKUFields(t *testing.T) {
|
||||||
|
request := &productv1.CreateProductRequest{
|
||||||
|
Title: "Product without business codes",
|
||||||
|
Skus: []*productv1.CreateProductSKU{
|
||||||
|
{
|
||||||
|
SkuNo: "SKU-REUSED",
|
||||||
|
Name: "Same SKU name",
|
||||||
|
Price: 100,
|
||||||
|
StockQuantity: 1,
|
||||||
|
K1: "Color",
|
||||||
|
V1: "Red",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
SkuNo: "SKU-REUSED",
|
||||||
|
Name: "Same SKU name",
|
||||||
|
Price: 200,
|
||||||
|
StockQuantity: 2,
|
||||||
|
K1: "Color",
|
||||||
|
V1: "Blue",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
product, skus, err := productFromCreateRequest(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("productFromCreateRequest() error = %v", err)
|
||||||
|
}
|
||||||
|
if product.SPUNo != "" {
|
||||||
|
t.Fatalf("SPUNo = %q, want empty", product.SPUNo)
|
||||||
|
}
|
||||||
|
if len(skus) != 2 || skus[0].SKUNo != skus[1].SKUNo || skus[0].Name != skus[1].Name {
|
||||||
|
t.Fatalf("repeated SKU fields were not preserved: %#v", skus)
|
||||||
|
}
|
||||||
|
}
|
||||||
82
internal/server/product_create_errors.go
Normal file
82
internal/server/product_create_errors.go
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
// productCreateError preserves the existing gRPC code and message, while
|
||||||
|
// attaching the field that failed validation for callers that understand the
|
||||||
|
// standard google.rpc.BadRequest detail.
|
||||||
|
func productCreateError(code codes.Code, message, field string) error {
|
||||||
|
if field == "" {
|
||||||
|
return status.Error(code, message)
|
||||||
|
}
|
||||||
|
grpcStatus := status.New(code, message)
|
||||||
|
withDetails, err := grpcStatus.WithDetails(&errdetails.BadRequest{
|
||||||
|
FieldViolations: []*errdetails.BadRequest_FieldViolation{{
|
||||||
|
Field: field,
|
||||||
|
Description: message,
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return grpcStatus.Err()
|
||||||
|
}
|
||||||
|
return withDetails.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func productMasterReferenceField(err error) string {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, repository.ErrBrandNotFound),
|
||||||
|
errors.Is(err, repository.ErrBrandInactive),
|
||||||
|
errors.Is(err, repository.ErrBrandSupplierMismatch):
|
||||||
|
return "brand_id"
|
||||||
|
case errors.Is(err, repository.ErrSupplierNotFound),
|
||||||
|
errors.Is(err, repository.ErrSupplierInactive):
|
||||||
|
return "supplier_id"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func productCreateFieldFromMessage(message string) string {
|
||||||
|
if strings.HasPrefix(message, "skus[") {
|
||||||
|
separator := strings.Index(message, ":")
|
||||||
|
if separator > 0 {
|
||||||
|
prefix := message[:separator]
|
||||||
|
detail := strings.TrimSpace(message[separator+1:])
|
||||||
|
for _, field := range []string{"supply_price", "weight_kg", "stock_quantity", "price", "status", "k1", "v1", "k2", "v2", "k3", "v3"} {
|
||||||
|
if strings.HasPrefix(detail, field) || strings.Contains(detail, field+"/") {
|
||||||
|
return prefix + "." + field
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return prefix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if message == "request is required" {
|
||||||
|
return "$"
|
||||||
|
}
|
||||||
|
if message == "unsupported product status" {
|
||||||
|
return "status"
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(message, "on-sale product") {
|
||||||
|
return "skus"
|
||||||
|
}
|
||||||
|
for _, field := range []string{
|
||||||
|
"title", "detail_html", "leaf_catalog_category_ids", "group_ids", "product_category_ids",
|
||||||
|
"freight_fixed_amount", "goods_type", "freight_charge_type", "freight_template_id",
|
||||||
|
"sale_time_type", "scheduled_sale_time", "presale_type", "purchase_limit_quantity",
|
||||||
|
"delivery_time_type", "delivery_start_at", "delivery_after_paid_days", "cross_border_info",
|
||||||
|
} {
|
||||||
|
if strings.HasPrefix(message, field) {
|
||||||
|
return field
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
43
internal/server/product_create_errors_test.go
Normal file
43
internal/server/product_create_errors_test.go
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductCreateErrorIncludesFieldViolation(t *testing.T) {
|
||||||
|
err := productCreateError(codes.InvalidArgument, "price must be greater than or equal to 0", "skus[0].price")
|
||||||
|
grpcStatus := status.Convert(err)
|
||||||
|
if grpcStatus.Code() != codes.InvalidArgument || grpcStatus.Message() != "price must be greater than or equal to 0" {
|
||||||
|
t.Fatalf("status = (%s, %q)", grpcStatus.Code(), grpcStatus.Message())
|
||||||
|
}
|
||||||
|
details := grpcStatus.Details()
|
||||||
|
if len(details) != 1 {
|
||||||
|
t.Fatalf("details count = %d, want 1", len(details))
|
||||||
|
}
|
||||||
|
badRequest, ok := details[0].(*errdetails.BadRequest)
|
||||||
|
if !ok || len(badRequest.GetFieldViolations()) != 1 {
|
||||||
|
t.Fatalf("details = %#v", details)
|
||||||
|
}
|
||||||
|
violation := badRequest.GetFieldViolations()[0]
|
||||||
|
if violation.GetField() != "skus[0].price" || violation.GetDescription() != grpcStatus.Message() {
|
||||||
|
t.Fatalf("violation = %#v", violation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductCreateFieldFromMessage(t *testing.T) {
|
||||||
|
tests := map[string]string{
|
||||||
|
"title is required": "title",
|
||||||
|
"skus[2]: price must be greater than or equal to 0": "skus[2].price",
|
||||||
|
"cross_border_info.logistics_mode is invalid": "cross_border_info",
|
||||||
|
"delivery_start_at is required when delivery_time_type is 1": "delivery_start_at",
|
||||||
|
}
|
||||||
|
for message, want := range tests {
|
||||||
|
if got := productCreateFieldFromMessage(message); got != want {
|
||||||
|
t.Errorf("productCreateFieldFromMessage(%q) = %q, want %q", message, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
19
internal/server/product_cross_border_test.go
Normal file
19
internal/server/product_cross_border_test.go
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCrossBorderJSONRoundTripsPortCode(t *testing.T) {
|
||||||
|
raw, err := crossBorderJSONFromProto(&productv1.CrossBorderInfo{
|
||||||
|
PortCode: "3100",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal cross-border info: %v", err)
|
||||||
|
}
|
||||||
|
if got := toProtoCrossBorderInfo(raw).GetPortCode(); got != "3100" {
|
||||||
|
t.Fatalf("round-trip port_code = %q, want %q", got, "3100")
|
||||||
|
}
|
||||||
|
}
|
||||||
83
internal/server/product_freight_charge_test.go
Normal file
83
internal/server/product_freight_charge_test.go
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProductFreightChargeFromUpdateRequest(t *testing.T) {
|
||||||
|
fixedAmount := int64(1000)
|
||||||
|
templateID := "2114688315977371648"
|
||||||
|
tooLongSPU := strings.Repeat("a", 101)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
req *productv1.UpdateProductFreightChargeRequest
|
||||||
|
wantErr string
|
||||||
|
wantType int32
|
||||||
|
wantFee int64
|
||||||
|
wantID string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "fixed freight",
|
||||||
|
req: &productv1.UpdateProductFreightChargeRequest{
|
||||||
|
SpuNo: " SPU-001 ",
|
||||||
|
FreightChargeType: 1,
|
||||||
|
FreightFixedAmount: &fixedAmount,
|
||||||
|
},
|
||||||
|
wantType: 1,
|
||||||
|
wantFee: 1000,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "freight template",
|
||||||
|
req: &productv1.UpdateProductFreightChargeRequest{
|
||||||
|
SpuNo: "SPU-001",
|
||||||
|
FreightChargeType: 2,
|
||||||
|
FreightTemplateId: &templateID,
|
||||||
|
},
|
||||||
|
wantType: 2,
|
||||||
|
wantID: templateID,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "fixed freight needs amount",
|
||||||
|
req: &productv1.UpdateProductFreightChargeRequest{
|
||||||
|
SpuNo: "SPU-001", FreightChargeType: 1,
|
||||||
|
},
|
||||||
|
wantErr: "freight_fixed_amount is required",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "template mode rejects amount",
|
||||||
|
req: &productv1.UpdateProductFreightChargeRequest{
|
||||||
|
SpuNo: "SPU-001", FreightChargeType: 2, FreightFixedAmount: &fixedAmount, FreightTemplateId: &templateID,
|
||||||
|
},
|
||||||
|
wantErr: "freight_fixed_amount must be omitted",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "spu cannot exceed limit",
|
||||||
|
req: &productv1.UpdateProductFreightChargeRequest{
|
||||||
|
SpuNo: tooLongSPU, FreightChargeType: 1, FreightFixedAmount: &fixedAmount,
|
||||||
|
},
|
||||||
|
wantErr: "spu_no must contain at most 100 characters",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
spuNo, chargeType, fee, gotTemplateID, err := productFreightChargeFromUpdateRequest(tt.req)
|
||||||
|
if tt.wantErr != "" {
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||||
|
t.Fatalf("error = %v, want containing %q", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("productFreightChargeFromUpdateRequest() error = %v", err)
|
||||||
|
}
|
||||||
|
if spuNo != "SPU-001" || chargeType != tt.wantType || fee != tt.wantFee || gotTemplateID != tt.wantID {
|
||||||
|
t.Fatalf("result = (%q, %d, %d, %q), want (%q, %d, %d, %q)", spuNo, chargeType, fee, gotTemplateID, "SPU-001", tt.wantType, tt.wantFee, tt.wantID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
83
internal/server/product_presale_configuration_test.go
Normal file
83
internal/server/product_presale_configuration_test.go
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidateProductDeliveryConfiguration(t *testing.T) {
|
||||||
|
scheduled := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
product repository.ProductRecord
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "specified delivery time",
|
||||||
|
product: repository.ProductRecord{
|
||||||
|
PresaleType: 1,
|
||||||
|
DeliveryTimeType: 1,
|
||||||
|
DeliveryStartAt: &scheduled,
|
||||||
|
PurchaseLimitQuantity: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "after paid days",
|
||||||
|
product: repository.ProductRecord{
|
||||||
|
PresaleType: 2,
|
||||||
|
DeliveryTimeType: 2,
|
||||||
|
DeliveryAfterPaidDays: 7,
|
||||||
|
PurchaseLimitQuantity: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "specified delivery time requires date",
|
||||||
|
product: repository.ProductRecord{
|
||||||
|
DeliveryTimeType: 1,
|
||||||
|
},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "after paid days must be positive",
|
||||||
|
product: repository.ProductRecord{
|
||||||
|
DeliveryTimeType: 2,
|
||||||
|
DeliveryAfterPaidDays: 0,
|
||||||
|
},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "purchase limit cannot be negative",
|
||||||
|
product: repository.ProductRecord{
|
||||||
|
PurchaseLimitQuantity: -1,
|
||||||
|
},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
product := tt.product
|
||||||
|
err := validateProductDeliveryConfiguration(&product)
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Fatalf("validateProductDeliveryConfiguration() error = %v, wantErr %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateProductDeliveryConfigurationClearsInapplicableValues(t *testing.T) {
|
||||||
|
scheduled := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
product := repository.ProductRecord{
|
||||||
|
DeliveryTimeType: 0,
|
||||||
|
DeliveryStartAt: &scheduled,
|
||||||
|
DeliveryAfterPaidDays: 5,
|
||||||
|
}
|
||||||
|
if err := validateProductDeliveryConfiguration(&product); err != nil {
|
||||||
|
t.Fatalf("validateProductDeliveryConfiguration() error = %v", err)
|
||||||
|
}
|
||||||
|
if product.DeliveryStartAt != nil || product.DeliveryAfterPaidDays != 0 {
|
||||||
|
t.Fatalf("inapplicable delivery values were not cleared: %#v", product)
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
43
internal/server/scheduled_sale_worker.go
Normal file
43
internal/server/scheduled_sale_worker.go
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StartScheduledSaleWorker periodically promotes due scheduled products to ON_SALE.
|
||||||
|
func StartScheduledSaleWorker(ctx context.Context, repo *repository.ProductRepository, logger *zap.Logger, interval time.Duration) {
|
||||||
|
if interval <= 0 {
|
||||||
|
interval = time.Minute
|
||||||
|
}
|
||||||
|
if logger == nil {
|
||||||
|
logger = zap.NewNop()
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(interval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
run := func() {
|
||||||
|
n, err := repo.PromoteDueScheduledSales(ctx, time.Now().UTC())
|
||||||
|
if err != nil {
|
||||||
|
logger.Error("promote scheduled sales failed", zap.Error(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
logger.Info("promoted scheduled sales", zap.Int64("count", n))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
run()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
44
internal/server/store_scope.go
Normal file
44
internal/server/store_scope.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
|
||||||
|
commonv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/common/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
type storeContextGetter interface {
|
||||||
|
GetStoreContext() *commonv1.StoreContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireStoreScope(req storeContextGetter) (repository.StoreScope, error) {
|
||||||
|
if req == nil {
|
||||||
|
return repository.StoreScope{}, status.Error(codes.FailedPrecondition, "store_context is required")
|
||||||
|
}
|
||||||
|
sc := req.GetStoreContext()
|
||||||
|
if sc == nil || strings.TrimSpace(sc.GetStoreId()) == "" || strings.TrimSpace(sc.GetTenantId()) == "" {
|
||||||
|
return repository.StoreScope{}, status.Error(codes.FailedPrecondition, "store_context.store_id and tenant_id are required")
|
||||||
|
}
|
||||||
|
storeID, err := parsePositiveID(strings.TrimSpace(sc.GetStoreId()), "store_context.store_id")
|
||||||
|
if err != nil {
|
||||||
|
return repository.StoreScope{}, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
tenantID, err := parsePositiveID(strings.TrimSpace(sc.GetTenantId()), "store_context.tenant_id")
|
||||||
|
if err != nil {
|
||||||
|
return repository.StoreScope{}, status.Error(codes.InvalidArgument, err.Error())
|
||||||
|
}
|
||||||
|
return repository.StoreScope{TenantID: tenantID, StoreID: storeID}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePositiveID(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
|
||||||
|
}
|
||||||
61
internal/server/store_scope_test.go
Normal file
61
internal/server/store_scope_test.go
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
|
|
||||||
|
commonv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/common/v1"
|
||||||
|
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||||
|
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRequireStoreScopeMissing(t *testing.T) {
|
||||||
|
_, err := requireStoreScope(&productv1.GetProductRequest{ProductId: "1"})
|
||||||
|
if status.Code(err) != codes.FailedPrecondition {
|
||||||
|
t.Fatalf("code = %v, want FailedPrecondition", status.Code(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetProductBySkuRequiresStoreContext(t *testing.T) {
|
||||||
|
s := NewProductServer(nil, nil, nil, nil)
|
||||||
|
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{})
|
||||||
|
if status.Code(err) != codes.FailedPrecondition {
|
||||||
|
t.Fatalf("err = %v, want FailedPrecondition", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetProductBySkuRequiresID(t *testing.T) {
|
||||||
|
s := NewProductServer(nil, nil, nil, nil)
|
||||||
|
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{
|
||||||
|
StoreContext: &commonv1.StoreContext{TenantId: "10", StoreId: "20"},
|
||||||
|
})
|
||||||
|
if status.Code(err) != codes.InvalidArgument {
|
||||||
|
t.Fatalf("err = %v, want InvalidArgument", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductCopyMaterialMapRequiresExactCoverage(t *testing.T) {
|
||||||
|
product := &repository.ProductRecord{ImageIDs: []string{"100"}}
|
||||||
|
skus := []repository.SKURecord{{ImageIDs: []string{"200", "100"}}}
|
||||||
|
|
||||||
|
mappings, err := productCopyMaterialMap(product, skus, []*productv1.MaterialIDMapping{
|
||||||
|
{SourceMaterialId: "100", TargetMaterialId: "300"},
|
||||||
|
{SourceMaterialId: "200", TargetMaterialId: "400"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("productCopyMaterialMap() error = %v", err)
|
||||||
|
}
|
||||||
|
if mappings["100"] != "300" || mappings["200"] != "400" {
|
||||||
|
t.Fatalf("mappings = %#v", mappings)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = productCopyMaterialMap(product, skus, []*productv1.MaterialIDMapping{
|
||||||
|
{SourceMaterialId: "100", TargetMaterialId: "300"},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("productCopyMaterialMap() error = nil, want missing mapping error")
|
||||||
|
}
|
||||||
|
}
|
||||||
90
scripts/sql/006_rebuild_standard_product_category_tree.sql
Normal file
90
scripts/sql/006_rebuild_standard_product_category_tree.sql
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
-- Rebuild product.product_category as the global standard product taxonomy.
|
||||||
|
--
|
||||||
|
-- DESTRUCTIVE: this script permanently removes every legacy store-scoped
|
||||||
|
-- product category and every product-category binding. Product, SKU, catalog
|
||||||
|
-- category, and product-group data are not removed. Run during a maintenance
|
||||||
|
-- window, after taking a database backup, and before importing the new tree.
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS product.product_category_bindings;
|
||||||
|
DROP TABLE IF EXISTS product.product_category;
|
||||||
|
|
||||||
|
CREATE TABLE product.product_category (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
level SMALLINT NOT NULL CHECK (level >= 1),
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
priority INTEGER NOT NULL DEFAULT 0,
|
||||||
|
rule_id VARCHAR(64) NOT NULL,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
category_type SMALLINT NOT NULL,
|
||||||
|
channel_list INTEGER[] NOT NULL DEFAULT '{}'::INTEGER[],
|
||||||
|
has_children BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
has_prop_required BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
extra TEXT NOT NULL DEFAULT '',
|
||||||
|
cert_status_code INTEGER NOT NULL,
|
||||||
|
cert_status_pass BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
cert_status_msg VARCHAR(500) NOT NULL DEFAULT '',
|
||||||
|
platform_category_id BIGINT NOT NULL CHECK (platform_category_id > 0),
|
||||||
|
platform_parent_category_id BIGINT NOT NULL CHECK (platform_parent_category_id >= 0),
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ,
|
||||||
|
CONSTRAINT chk_product_category_hierarchy CHECK (
|
||||||
|
(parent_id IS NULL AND level = 1)
|
||||||
|
OR (parent_id IS NOT NULL AND level > 1)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_product_category_active_parent_priority
|
||||||
|
ON product.product_category (parent_id, priority, id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX idx_product_category_active_status_parent_priority
|
||||||
|
ON product.product_category (status, parent_id, priority, id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX idx_product_category_rule_id
|
||||||
|
ON product.product_category (rule_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX uq_product_category_active_platform_category
|
||||||
|
ON product.product_category (platform_category_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX idx_product_category_active_platform_parent_category
|
||||||
|
ON product.product_category (platform_parent_category_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX idx_product_category_channel_list
|
||||||
|
ON product.product_category USING GIN (channel_list);
|
||||||
|
|
||||||
|
CREATE TABLE product.product_category_bindings (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||||
|
product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_product_category_bindings_active
|
||||||
|
ON product.product_category_bindings (product_id, product_category_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX idx_product_category_bindings_category
|
||||||
|
ON product.product_category_bindings (store_id, product_category_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX idx_product_category_bindings_product
|
||||||
|
ON product.product_category_bindings (store_id, product_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_product_category_updated_at ON product.product_category;
|
||||||
|
CREATE TRIGGER set_product_category_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_category
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_product_category_bindings_updated_at ON product.product_category_bindings;
|
||||||
|
CREATE TRIGGER set_product_category_bindings_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_category_bindings
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
11
scripts/sql/007_catalog_category_multilevel_tree.sql
Normal file
11
scripts/sql/007_catalog_category_multilevel_tree.sql
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
-- Enables efficient lazy administration and full storefront traversal for the
|
||||||
|
-- existing multi-level capable catalog_category adjacency list. Existing
|
||||||
|
-- two-level records require no data migration. The product service executes
|
||||||
|
-- the same idempotent statements during EnsureSchema on every startup; retain
|
||||||
|
-- this file for release pipelines or standalone database operations.
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_parent_status_sort
|
||||||
|
ON product.catalog_category (store_id, node_type, parent_id, status, sort_num, id);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN product.catalog_category.level IS
|
||||||
|
'Server-maintained hierarchy level: root is 1 and each child is parent level plus 1.';
|
||||||
23
scripts/sql/008_product_presale_delivery_purchase_limit.sql
Normal file
23
scripts/sql/008_product_presale_delivery_purchase_limit.sql
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
-- Product presale labels, delivery promises and per-customer purchase limits.
|
||||||
|
-- This migration is intentionally idempotent and matches EnsureSchema.
|
||||||
|
|
||||||
|
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS presale_type SMALLINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_time_type SMALLINT NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_start_at TIMESTAMPTZ;
|
||||||
|
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS delivery_after_paid_days INTEGER;
|
||||||
|
ALTER TABLE product.products ADD COLUMN IF NOT EXISTS purchase_limit_quantity INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
ALTER TABLE product.products DROP CONSTRAINT IF EXISTS chk_products_presale_configuration;
|
||||||
|
ALTER TABLE product.products ADD CONSTRAINT chk_products_presale_configuration CHECK (
|
||||||
|
presale_type IN (0, 1, 2)
|
||||||
|
AND purchase_limit_quantity >= 0
|
||||||
|
AND (
|
||||||
|
(delivery_time_type = 0 AND delivery_start_at IS NULL AND delivery_after_paid_days IS NULL)
|
||||||
|
OR (delivery_time_type = 1 AND delivery_start_at IS NOT NULL AND delivery_after_paid_days IS NULL)
|
||||||
|
OR (delivery_time_type = 2 AND delivery_start_at IS NULL AND delivery_after_paid_days > 0)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_store_presale_created_id
|
||||||
|
ON product.products (store_id, presale_type, created_at DESC, id DESC)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
10
scripts/sql/009_catalog_category_created_at.sql
Normal file
10
scripts/sql/009_catalog_category_created_at.sql
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
-- Adds audit timestamps required by the product-group list's
|
||||||
|
-- created_at-descending pagination. This migration is idempotent and the
|
||||||
|
-- product service also executes the same statements in EnsureSchema.
|
||||||
|
|
||||||
|
ALTER TABLE product.catalog_category
|
||||||
|
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
|
||||||
|
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC);
|
||||||
49
scripts/sql/010_catalog_category_binding_audit_fields.sql
Normal file
49
scripts/sql/010_catalog_category_binding_audit_fields.sql
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
-- Adds audit timestamps and soft-delete support to storefront catalog nodes
|
||||||
|
-- and their product bindings. The statements are idempotent and mirror the
|
||||||
|
-- product service's EnsureSchema upgrade path.
|
||||||
|
|
||||||
|
ALTER TABLE product.catalog_category
|
||||||
|
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||||
|
|
||||||
|
ALTER TABLE product.product_catalog_bindings
|
||||||
|
ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||||
|
|
||||||
|
ALTER TABLE product.product_catalog_bindings
|
||||||
|
DROP CONSTRAINT IF EXISTS uq_product_catalog_bindings_product_category;
|
||||||
|
ALTER TABLE product.product_catalog_bindings
|
||||||
|
DROP CONSTRAINT IF EXISTS uq_product_category_bindings_product_category;
|
||||||
|
|
||||||
|
DROP INDEX IF EXISTS product.uq_product_catalog_bindings_product_category;
|
||||||
|
DROP INDEX IF EXISTS product.uq_product_category_bindings_product_category;
|
||||||
|
DROP INDEX IF EXISTS product.idx_product_catalog_bindings_category_id;
|
||||||
|
DROP INDEX IF EXISTS product.idx_catalog_category_store_type_created_id;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_catalog_bindings_active_product_category
|
||||||
|
ON product.product_catalog_bindings (product_id, category_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_catalog_bindings_category_id
|
||||||
|
ON product.product_catalog_bindings (category_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
|
||||||
|
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
DROP INDEX IF EXISTS product.uq_product_category_group_normalized_name;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
|
||||||
|
ON product.catalog_category (
|
||||||
|
store_id,
|
||||||
|
COALESCE(parent_id, 0),
|
||||||
|
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||||
|
) WHERE node_type = 2 AND deleted_at IS NULL;
|
||||||
|
|
||||||
|
DROP INDEX IF EXISTS product.uq_product_category_sibling_normalized_name;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name
|
||||||
|
ON product.catalog_category (
|
||||||
|
store_id,
|
||||||
|
COALESCE(parent_id, 0),
|
||||||
|
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||||
|
) WHERE node_type = 1 AND deleted_at IS NULL;
|
||||||
7
scripts/sql/011_add_products_is_distribution_product.sql
Normal file
7
scripts/sql/011_add_products_is_distribution_product.sql
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
-- Adds an explicit SPU-level distribution flag. Existing products remain
|
||||||
|
-- non-distribution products by default.
|
||||||
|
ALTER TABLE product.products
|
||||||
|
ADD COLUMN IF NOT EXISTS is_distribution_product BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN product.products.is_distribution_product
|
||||||
|
IS '是否为分销商品;FALSE 表示非分销商品';
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
-- 为已部署环境补充分销商品详情;JSONB 由数据库保证传入内容是合法 JSON。
|
||||||
|
ALTER TABLE product.products
|
||||||
|
ADD COLUMN IF NOT EXISTS distribution_product_detail JSONB NOT NULL DEFAULT '{}'::JSONB;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN product.products.distribution_product_detail
|
||||||
|
IS '分销商品详情 JSON;由后台原样保存业务提交的有效 JSON';
|
||||||
432
scripts/sql/02-product-schema.sql
Normal file
432
scripts/sql/02-product-schema.sql
Normal file
@ -0,0 +1,432 @@
|
|||||||
|
-- Product service complete schema.
|
||||||
|
-- Source of truth: the current ids-svc-product repository schema and its SQL migrations.
|
||||||
|
-- This script initializes an empty PostgreSQL database; it does not migrate legacy tables.
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
-- Product catalog tables.
|
||||||
|
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,
|
||||||
|
is_distribution_product BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
distribution_product_detail JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||||
|
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,
|
||||||
|
category_properties 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,
|
||||||
|
presale_type SMALLINT NOT NULL DEFAULT 0,
|
||||||
|
delivery_time_type SMALLINT NOT NULL DEFAULT 0,
|
||||||
|
delivery_start_at TIMESTAMPTZ,
|
||||||
|
delivery_after_paid_days INTEGER,
|
||||||
|
purchase_limit_quantity INTEGER NOT NULL DEFAULT 0,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0,
|
||||||
|
tenant_id BIGINT,
|
||||||
|
store_id BIGINT,
|
||||||
|
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_presale_configuration
|
||||||
|
CHECK (
|
||||||
|
presale_type IN (0, 1, 2)
|
||||||
|
AND purchase_limit_quantity >= 0
|
||||||
|
AND (
|
||||||
|
(delivery_time_type = 0 AND delivery_start_at IS NULL AND delivery_after_paid_days IS NULL)
|
||||||
|
OR (delivery_time_type = 1 AND delivery_start_at IS NOT NULL AND delivery_after_paid_days IS NULL)
|
||||||
|
OR (delivery_time_type = 2 AND delivery_start_at IS NULL AND delivery_after_paid_days > 0)
|
||||||
|
)
|
||||||
|
),
|
||||||
|
CONSTRAINT chk_products_version
|
||||||
|
CHECK (version >= 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.products IS '商品 SPU 主表:存储商品公共信息、品牌、供应商、图片、商品类型、运费、开售配置和软删除状态';
|
||||||
|
COMMENT ON COLUMN product.products.brand_id IS '品牌 ID,对应 product.brands.id;由应用层校验所属店铺及可用状态';
|
||||||
|
COMMENT ON COLUMN product.products.supplier_id IS '供应商 ID,对应 product.suppliers.id;由应用层校验所属店铺及可用状态';
|
||||||
|
COMMENT ON COLUMN product.products.service_guarantees IS '服务保障展示快照;服务保障主数据变更时需通过业务流程刷新';
|
||||||
|
COMMENT ON COLUMN product.products.detail_html IS '商品详情 HTML;写入或渲染前必须做 HTML Sanitization,列表接口不得读取该字段';
|
||||||
|
COMMENT ON COLUMN product.products.is_distribution_product IS '是否为分销商品;FALSE 表示非分销商品';
|
||||||
|
COMMENT ON COLUMN product.products.distribution_product_detail IS '分销商品详情 JSON;由后台原样保存业务提交的有效 JSON';
|
||||||
|
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_store_id
|
||||||
|
ON product.products (store_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_active_created_id
|
||||||
|
ON product.products (created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_products_store_active_created_id
|
||||||
|
ON product.products (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no
|
||||||
|
ON product.products (store_id, spu_no)
|
||||||
|
WHERE deleted_at IS NULL AND spu_no <> '';
|
||||||
|
|
||||||
|
-- Storefront catalog classification and product group tables.
|
||||||
|
CREATE TABLE IF NOT EXISTS product.catalog_category (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
node_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
parent_id BIGINT REFERENCES product.catalog_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,
|
||||||
|
tenant_id BIGINT,
|
||||||
|
store_id BIGINT,
|
||||||
|
campaign_id BIGINT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ,
|
||||||
|
CONSTRAINT chk_catalog_category_node_type
|
||||||
|
CHECK (node_type IN (1, 2)),
|
||||||
|
CONSTRAINT chk_catalog_category_level
|
||||||
|
CHECK (level > 0),
|
||||||
|
CONSTRAINT chk_catalog_category_status
|
||||||
|
CHECK (status IN (0, 1)),
|
||||||
|
CONSTRAINT chk_catalog_category_version
|
||||||
|
CHECK (version >= 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.catalog_category IS '商品目录分类及商品分组表,通过 node_type 区分分类或分组';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.node_type IS '节点类型:1 分类,2 分组';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.parent_id IS '上级节点 ID;顶级节点为空,分组通常为顶级节点';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.campaign_id IS '活动 ID;仅用于关联活动展示的分类或分组';
|
||||||
|
COMMENT ON COLUMN product.catalog_category.version IS '乐观锁版本号,更新时递增';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_parent_id
|
||||||
|
ON product.catalog_category (parent_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_node_status_sort
|
||||||
|
ON product.catalog_category (node_type, status, sort_num);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id
|
||||||
|
ON product.catalog_category (store_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_campaign_id
|
||||||
|
ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL AND deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
|
||||||
|
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
|
||||||
|
ON product.catalog_category (
|
||||||
|
store_id,
|
||||||
|
COALESCE(parent_id, 0),
|
||||||
|
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||||
|
) WHERE node_type = 2 AND deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_sibling_normalized_name
|
||||||
|
ON product.catalog_category (
|
||||||
|
store_id,
|
||||||
|
COALESCE(parent_id, 0),
|
||||||
|
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||||
|
) WHERE node_type = 1 AND deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_catalog_bindings (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||||
|
category_id BIGINT NOT NULL REFERENCES product.catalog_category(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_catalog_bindings IS '商品目录分类/分组绑定表:存储 SPU 与目录分类或分组节点的多对多关系';
|
||||||
|
COMMENT ON COLUMN product.product_catalog_bindings.product_id IS '商品 SPU ID,对应 product.products.id';
|
||||||
|
COMMENT ON COLUMN product.product_catalog_bindings.category_id IS '目录分类或分组节点 ID,对应 product.catalog_category.id';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_catalog_bindings_category_id
|
||||||
|
ON product.product_catalog_bindings (category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_catalog_bindings_active_product_category
|
||||||
|
ON product.product_catalog_bindings (product_id, category_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
-- Global standard product taxonomy. This taxonomy is distinct from catalog_category.
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_category (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
level SMALLINT NOT NULL CHECK (level >= 1),
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
priority INTEGER NOT NULL DEFAULT 0,
|
||||||
|
rule_id VARCHAR(64) NOT NULL,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
category_type SMALLINT NOT NULL,
|
||||||
|
channel_list INTEGER[] NOT NULL DEFAULT '{}'::INTEGER[],
|
||||||
|
has_children BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
has_prop_required BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
extra TEXT NOT NULL DEFAULT '',
|
||||||
|
cert_status_code INTEGER NOT NULL,
|
||||||
|
cert_status_pass BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
cert_status_msg VARCHAR(500) NOT NULL DEFAULT '',
|
||||||
|
platform_category_id BIGINT NOT NULL CHECK (platform_category_id > 0),
|
||||||
|
platform_parent_category_id BIGINT NOT NULL CHECK (platform_parent_category_id >= 0),
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ,
|
||||||
|
CONSTRAINT chk_product_category_hierarchy CHECK (
|
||||||
|
(parent_id IS NULL AND level = 1)
|
||||||
|
OR (parent_id IS NOT NULL AND level > 1)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_category IS '全局标准商品类目树,与目录分类/分组表独立';
|
||||||
|
COMMENT ON COLUMN product.product_category.platform_category_id IS '外部平台分类节点 ID;当前映射有赞响应节点的 id';
|
||||||
|
COMMENT ON COLUMN product.product_category.platform_parent_category_id IS '外部平台父分类 ID;当前映射有赞响应节点的 parentId,一级节点为 0';
|
||||||
|
COMMENT ON COLUMN product.product_category.has_children IS '上游声明的是否存在下级类目,不以本地直接子节点数量推断';
|
||||||
|
COMMENT ON COLUMN product.product_category.deleted_at IS '软删除时间;NULL 表示未删除';
|
||||||
|
|
||||||
|
-- Older installs may already have product_category without priority;
|
||||||
|
-- CREATE TABLE IF NOT EXISTS will not add it.
|
||||||
|
ALTER TABLE product.product_category
|
||||||
|
ADD COLUMN IF NOT EXISTS priority INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_active_parent_name
|
||||||
|
ON product.product_category (COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_active_parent_priority
|
||||||
|
ON product.product_category (parent_id, priority, id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_active_status_parent_priority
|
||||||
|
ON product.product_category (status, parent_id, priority, id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_rule_id
|
||||||
|
ON product.product_category (rule_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_active_platform_category
|
||||||
|
ON product.product_category (platform_category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_active_platform_parent_category
|
||||||
|
ON product.product_category (platform_parent_category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_channel_list
|
||||||
|
ON product.product_category USING GIN (channel_list);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_category_bindings (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||||
|
product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.product_category_bindings IS '商品标准类目绑定表:存储 SPU 与全局标准商品类目的多对多关系';
|
||||||
|
COMMENT ON COLUMN product.product_category_bindings.deleted_at IS '软删除时间,便于恢复历史绑定';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active
|
||||||
|
ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category
|
||||||
|
ON product.product_category_bindings (store_id, product_category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_product
|
||||||
|
ON product.product_category_bindings (store_id, product_category_id, product_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_product
|
||||||
|
ON product.product_category_bindings (store_id, product_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
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),
|
||||||
|
supply_price BIGINT CONSTRAINT chk_product_items_supply_price CHECK (supply_price >= 0),
|
||||||
|
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
|
attributes JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||||
|
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(),
|
||||||
|
tenant_id BIGINT,
|
||||||
|
store_id BIGINT,
|
||||||
|
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.supply_price IS 'SKU 供货价,单位:分;NULL 表示未维护';
|
||||||
|
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 AND is_archived = FALSE;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_items_store_id
|
||||||
|
ON product.product_items (store_id) WHERE deleted_at IS NULL;
|
||||||
|
-- SKU business codes are display/import data and are intentionally not unique.
|
||||||
|
|
||||||
|
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)
|
||||||
|
);
|
||||||
|
|
||||||
|
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 '库存乐观锁版本号';
|
||||||
|
|
||||||
|
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 待支付取消/超时释放锁定';
|
||||||
|
|
||||||
|
-- Supplier and brand master-data tables.
|
||||||
|
CREATE TABLE IF NOT EXISTS product.suppliers (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
alias VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
supplier_code VARCHAR(64) NOT NULL,
|
||||||
|
attachments JSONB NOT NULL DEFAULT '[]'::JSONB,
|
||||||
|
contact_name VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
contact_phone VARCHAR(32) NOT NULL DEFAULT '',
|
||||||
|
remark VARCHAR(1000) NOT NULL DEFAULT '',
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.suppliers IS '店铺供应商主数据表';
|
||||||
|
COMMENT ON COLUMN product.suppliers.attachments IS '供应商附件 JSON 数组,元素包含 file_id、file_name 和 file_type';
|
||||||
|
COMMENT ON COLUMN product.suppliers.status IS '供应商状态:0 停用,1 启用';
|
||||||
|
COMMENT ON COLUMN product.suppliers.deleted_at IS '软删除时间;NULL 表示未删除';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_suppliers_store_code_active
|
||||||
|
ON product.suppliers (store_id, supplier_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_suppliers_store_list
|
||||||
|
ON product.suppliers (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.brands (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
alias VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
brand_code VARCHAR(64) NOT NULL,
|
||||||
|
supplier_id BIGINT NOT NULL,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE product.brands IS '店铺品牌主数据表;supplier_id 由应用层约束到同店铺供应商,避免软删除外键限制';
|
||||||
|
COMMENT ON COLUMN product.brands.status IS '品牌状态:0 停用,1 启用';
|
||||||
|
COMMENT ON COLUMN product.brands.deleted_at IS '软删除时间;NULL 表示未删除';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_brands_store_code_active
|
||||||
|
ON product.brands (store_id, brand_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_brands_store_list
|
||||||
|
ON product.brands (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_brands_supplier
|
||||||
|
ON product.brands (store_id, supplier_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
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_category_updated_at ON product.product_category;
|
||||||
|
CREATE TRIGGER set_product_category_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_category
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_product_category_bindings_updated_at ON product.product_category_bindings;
|
||||||
|
CREATE TRIGGER set_product_category_bindings_updated_at
|
||||||
|
BEFORE UPDATE ON product.product_category_bindings
|
||||||
|
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();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_suppliers_updated_at ON product.suppliers;
|
||||||
|
CREATE TRIGGER set_suppliers_updated_at
|
||||||
|
BEFORE UPDATE ON product.suppliers
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_brands_updated_at ON product.brands;
|
||||||
|
CREATE TRIGGER set_brands_updated_at
|
||||||
|
BEFORE UPDATE ON product.brands
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA product TO svc_product;
|
||||||
14
scripts/sql/add-product-item-supply-price.sql
Normal file
14
scripts/sql/add-product-item-supply-price.sql
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
-- Adds the nullable SKU supply price without modifying historical values.
|
||||||
|
-- Amounts are stored in cents; NULL means the supply price has not been maintained.
|
||||||
|
ALTER TABLE product.product_items
|
||||||
|
ADD COLUMN IF NOT EXISTS supply_price BIGINT;
|
||||||
|
|
||||||
|
ALTER TABLE product.product_items
|
||||||
|
DROP CONSTRAINT IF EXISTS chk_product_items_supply_price;
|
||||||
|
|
||||||
|
ALTER TABLE product.product_items
|
||||||
|
ADD CONSTRAINT chk_product_items_supply_price
|
||||||
|
CHECK (supply_price IS NULL OR supply_price >= 0);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN product.product_items.supply_price
|
||||||
|
IS 'SKU 供货价,单位:分;NULL 表示未维护';
|
||||||
10
scripts/sql/add-product-list-filter-indexes.sql
Normal file
10
scripts/sql/add-product-list-filter-indexes.sql
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
-- Index supporting admin product list filters.
|
||||||
|
-- Run outside a transaction because CREATE INDEX CONCURRENTLY is used.
|
||||||
|
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_products_store_active_created_id
|
||||||
|
ON product.products (store_id, created_at DESC, id DESC)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_category_bindings_category_product
|
||||||
|
ON product.product_category_bindings (store_id, product_category_id, product_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
17
scripts/sql/migrate-product-code-constraints.sql
Normal file
17
scripts/sql/migrate-product-code-constraints.sql
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
-- One-time migration for optional SPU codes and non-unique SKU business codes.
|
||||||
|
-- Run during a maintenance window before deploying the corresponding service code.
|
||||||
|
-- CREATE/DROP INDEX CONCURRENTLY must not be wrapped in a transaction.
|
||||||
|
|
||||||
|
-- Empty SPU codes are allowed multiple times in one store. Non-empty active
|
||||||
|
-- product codes remain unique within their store.
|
||||||
|
DROP INDEX CONCURRENTLY IF EXISTS product.uq_products_spu_no;
|
||||||
|
DROP INDEX CONCURRENTLY IF EXISTS product.uq_products_store_spu_no;
|
||||||
|
CREATE UNIQUE INDEX CONCURRENTLY uq_products_store_spu_no
|
||||||
|
ON product.products (store_id, spu_no)
|
||||||
|
WHERE deleted_at IS NULL AND spu_no <> '';
|
||||||
|
|
||||||
|
-- SKU business codes are not identifiers and may repeat, including among
|
||||||
|
-- active SKUs in the same store. SKU primary keys remain the stable identity.
|
||||||
|
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;
|
||||||
|
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no_active;
|
||||||
|
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_store_sku_no_active;
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
-- Adds category property storage and allows group names to repeat under
|
||||||
|
-- different parents. Run this migration before deploying the application.
|
||||||
|
|
||||||
|
ALTER TABLE product.products
|
||||||
|
ADD COLUMN IF NOT EXISTS category_properties JSONB NOT NULL DEFAULT '{}'::JSONB;
|
||||||
|
|
||||||
|
DROP INDEX IF EXISTS product.uq_product_category_group_normalized_name;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_group_normalized_name
|
||||||
|
ON product.catalog_category (
|
||||||
|
store_id,
|
||||||
|
COALESCE(parent_id, 0),
|
||||||
|
lower(btrim(regexp_replace(translate(name, ' ', ' '), '[[:space:]]+', ' ', 'g')))
|
||||||
|
)
|
||||||
|
WHERE node_type = 2;
|
||||||
@ -1,6 +1,6 @@
|
|||||||
-- One-time migration for product lifecycle statuses and SKU archival.
|
-- One-time migration for product lifecycle statuses and SKU archival.
|
||||||
-- Run during a maintenance window before deploying the product-service code
|
-- Run during a maintenance window before deploying the product-service code
|
||||||
-- that uses PRODUCT_STATUS_INVENTORY / ON_SALE / OFF_SALE.
|
-- that uses PRODUCT_STATUS_INVENTORY / ON_SALE / SOLD_OUT.
|
||||||
|
|
||||||
BEGIN;
|
BEGIN;
|
||||||
|
|
||||||
@ -20,7 +20,7 @@ ALTER TABLE product.product_items
|
|||||||
ALTER TABLE product.products
|
ALTER TABLE product.products
|
||||||
DROP CONSTRAINT IF EXISTS chk_products_status;
|
DROP CONSTRAINT IF EXISTS chk_products_status;
|
||||||
|
|
||||||
-- Current values are 0=DRAFT, 1=ON_SALE, 3=OFF_SALE. Value 2 has no
|
-- Current values are 0=DRAFT, 1=ON_SALE, 3=SOLD_OUT. Value 2 has no
|
||||||
-- supported current meaning and is moved to INVENTORY as the safe state.
|
-- supported current meaning and is moved to INVENTORY as the safe state.
|
||||||
UPDATE product.products
|
UPDATE product.products
|
||||||
SET status = CASE status
|
SET status = CASE status
|
||||||
@ -38,17 +38,14 @@ ALTER TABLE product.products
|
|||||||
|
|
||||||
COMMIT;
|
COMMIT;
|
||||||
|
|
||||||
-- CREATE INDEX CONCURRENTLY cannot run inside the transaction above.
|
-- SKU business codes are no longer unique. Remove the legacy uniqueness index
|
||||||
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_product_items_sku_no_active
|
-- when this migration is applied to an existing deployment.
|
||||||
ON product.product_items (sku_no)
|
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no_active;
|
||||||
WHERE sku_no IS NOT NULL
|
|
||||||
AND deleted_at IS NULL
|
|
||||||
AND is_archived = FALSE;
|
|
||||||
|
|
||||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_items_active_product_id
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_items_active_product_id
|
||||||
ON product.product_items (product_id)
|
ON product.product_items (product_id)
|
||||||
WHERE deleted_at IS NULL
|
WHERE deleted_at IS NULL
|
||||||
AND is_archived = FALSE;
|
AND is_archived = FALSE;
|
||||||
|
|
||||||
-- Drop the legacy index only after uq_product_items_sku_no_active is valid.
|
-- Remove the older legacy index as well, if it is still present.
|
||||||
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;
|
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;
|
||||||
|
|||||||
@ -3,6 +3,8 @@
|
|||||||
--
|
--
|
||||||
-- Tables:
|
-- Tables:
|
||||||
-- product.products
|
-- product.products
|
||||||
|
-- product.catalog_category
|
||||||
|
-- product.product_catalog_bindings
|
||||||
-- product.product_category
|
-- product.product_category
|
||||||
-- product.product_category_bindings
|
-- product.product_category_bindings
|
||||||
-- product.product_items
|
-- product.product_items
|
||||||
@ -15,6 +17,7 @@
|
|||||||
-- Drop order, if needed:
|
-- Drop order, if needed:
|
||||||
-- DROP TABLE IF EXISTS product.product_item_inventory;
|
-- DROP TABLE IF EXISTS product.product_item_inventory;
|
||||||
-- DROP TABLE IF EXISTS product.product_category_bindings;
|
-- DROP TABLE IF EXISTS product.product_category_bindings;
|
||||||
|
-- DROP TABLE IF EXISTS product.product_catalog_bindings;
|
||||||
-- DROP TABLE IF EXISTS product.product_items;
|
-- DROP TABLE IF EXISTS product.product_items;
|
||||||
-- DROP TABLE IF EXISTS product.product_category;
|
-- DROP TABLE IF EXISTS product.product_category;
|
||||||
-- DROP TABLE IF EXISTS product.products;
|
-- DROP TABLE IF EXISTS product.products;
|
||||||
@ -45,15 +48,23 @@ CREATE TABLE IF NOT EXISTS product.products (
|
|||||||
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
detail_html TEXT,
|
detail_html TEXT,
|
||||||
member_discount_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
member_discount_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
is_distribution_product BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
distribution_product_detail JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||||
goods_type SMALLINT NOT NULL DEFAULT 1,
|
goods_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
status SMALLINT NOT NULL DEFAULT 1,
|
status SMALLINT NOT NULL DEFAULT 1,
|
||||||
cross_border JSONB NOT NULL DEFAULT '{}'::JSONB,
|
cross_border JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||||
|
category_properties JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||||
freight_charge_type SMALLINT NOT NULL DEFAULT 1,
|
freight_charge_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
freight_fixed_amount BIGINT NOT NULL DEFAULT 0,
|
freight_fixed_amount BIGINT NOT NULL DEFAULT 0,
|
||||||
freight_template_id BIGINT,
|
freight_template_id BIGINT,
|
||||||
sale_time_type SMALLINT NOT NULL DEFAULT 1,
|
sale_time_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
scheduled_sale_time TIMESTAMPTZ,
|
scheduled_sale_time TIMESTAMPTZ,
|
||||||
|
presale_type SMALLINT NOT NULL DEFAULT 0,
|
||||||
|
delivery_time_type SMALLINT NOT NULL DEFAULT 0,
|
||||||
|
delivery_start_at TIMESTAMPTZ,
|
||||||
|
delivery_after_paid_days INTEGER,
|
||||||
|
purchase_limit_quantity INTEGER NOT NULL DEFAULT 0,
|
||||||
version INTEGER NOT NULL DEFAULT 0,
|
version INTEGER NOT NULL DEFAULT 0,
|
||||||
deleted_at TIMESTAMPTZ,
|
deleted_at TIMESTAMPTZ,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
@ -72,6 +83,16 @@ CREATE TABLE IF NOT EXISTS product.products (
|
|||||||
CHECK (sale_time_type IN (1, 2)),
|
CHECK (sale_time_type IN (1, 2)),
|
||||||
CONSTRAINT chk_products_scheduled_sale_time_required
|
CONSTRAINT chk_products_scheduled_sale_time_required
|
||||||
CHECK (sale_time_type <> 2 OR scheduled_sale_time IS NOT NULL),
|
CHECK (sale_time_type <> 2 OR scheduled_sale_time IS NOT NULL),
|
||||||
|
CONSTRAINT chk_products_presale_configuration
|
||||||
|
CHECK (
|
||||||
|
presale_type IN (0, 1, 2)
|
||||||
|
AND purchase_limit_quantity >= 0
|
||||||
|
AND (
|
||||||
|
(delivery_time_type = 0 AND delivery_start_at IS NULL AND delivery_after_paid_days IS NULL)
|
||||||
|
OR (delivery_time_type = 1 AND delivery_start_at IS NOT NULL AND delivery_after_paid_days IS NULL)
|
||||||
|
OR (delivery_time_type = 2 AND delivery_start_at IS NULL AND delivery_after_paid_days > 0)
|
||||||
|
)
|
||||||
|
),
|
||||||
CONSTRAINT chk_products_version
|
CONSTRAINT chk_products_version
|
||||||
CHECK (version >= 0)
|
CHECK (version >= 0)
|
||||||
);
|
);
|
||||||
@ -107,18 +128,24 @@ CREATE INDEX IF NOT EXISTS idx_products_active_created_id
|
|||||||
|
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no
|
||||||
ON product.products (spu_no)
|
ON product.products (spu_no)
|
||||||
WHERE deleted_at IS NULL;
|
WHERE deleted_at IS NULL AND spu_no <> '';
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS product.product_category (
|
CREATE TABLE IF NOT EXISTS product.catalog_category (
|
||||||
id BIGINT PRIMARY KEY,
|
id BIGINT PRIMARY KEY,
|
||||||
node_type SMALLINT NOT NULL DEFAULT 1,
|
node_type SMALLINT NOT NULL DEFAULT 1,
|
||||||
name VARCHAR(100) NOT NULL,
|
name VARCHAR(100) NOT NULL,
|
||||||
parent_id BIGINT REFERENCES product.product_category(id),
|
parent_id BIGINT REFERENCES product.catalog_category(id),
|
||||||
level SMALLINT NOT NULL,
|
level SMALLINT NOT NULL,
|
||||||
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
sort_num INTEGER NOT NULL DEFAULT 0,
|
sort_num INTEGER NOT NULL DEFAULT 0,
|
||||||
status SMALLINT NOT NULL DEFAULT 1,
|
status SMALLINT NOT NULL DEFAULT 1,
|
||||||
version INTEGER NOT NULL DEFAULT 0,
|
version INTEGER NOT NULL DEFAULT 0,
|
||||||
|
tenant_id BIGINT,
|
||||||
|
store_id BIGINT,
|
||||||
|
campaign_id BIGINT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ,
|
||||||
CONSTRAINT chk_product_category_node_type
|
CONSTRAINT chk_product_category_node_type
|
||||||
CHECK (node_type IN (1, 2)),
|
CHECK (node_type IN (1, 2)),
|
||||||
CONSTRAINT chk_product_category_level
|
CONSTRAINT chk_product_category_level
|
||||||
@ -129,37 +156,80 @@ CREATE TABLE IF NOT EXISTS product.product_category (
|
|||||||
CHECK (version >= 0)
|
CHECK (version >= 0)
|
||||||
);
|
);
|
||||||
|
|
||||||
COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组';
|
COMMENT ON TABLE product.catalog_category IS '商品目录分类表:存储原商品分类和商品分组,通过 node_type 区分分类或分组';
|
||||||
COMMENT ON COLUMN product.product_category.id IS '类别/分组节点主键';
|
COMMENT ON COLUMN product.catalog_category.id IS '类别/分组节点主键';
|
||||||
COMMENT ON COLUMN product.product_category.node_type IS '节点类型:1 分类,2 分组';
|
COMMENT ON COLUMN product.catalog_category.node_type IS '节点类型:1 分类,2 分组';
|
||||||
COMMENT ON COLUMN product.product_category.name IS '节点展示名称';
|
COMMENT ON COLUMN product.catalog_category.name IS '节点展示名称';
|
||||||
COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询';
|
COMMENT ON COLUMN product.catalog_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询';
|
||||||
COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3';
|
COMMENT ON COLUMN product.catalog_category.level IS '节点层级,如 1、2、3';
|
||||||
COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示';
|
COMMENT ON COLUMN product.catalog_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示';
|
||||||
COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前';
|
COMMENT ON COLUMN product.catalog_category.sort_num IS '排序值,数值越小越靠前';
|
||||||
COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示';
|
COMMENT ON COLUMN product.catalog_category.status IS '节点状态:0 隐藏,1 显示';
|
||||||
COMMENT ON COLUMN product.product_category.version IS '节点乐观锁版本号,更新时递增';
|
COMMENT ON COLUMN product.catalog_category.version IS '节点乐观锁版本号,更新时递增';
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_product_category_parent_id
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_parent_id
|
||||||
ON product.product_category (parent_id);
|
ON product.catalog_category (parent_id);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_node_status_sort
|
||||||
ON product.product_category (node_type, status, sort_num);
|
ON product.catalog_category (node_type, status, sort_num) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_created_id
|
||||||
|
ON product.catalog_category (store_id, node_type, created_at DESC, id DESC)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS product.product_category_bindings (
|
CREATE TABLE IF NOT EXISTS product.product_catalog_bindings (
|
||||||
id BIGINT PRIMARY KEY,
|
id BIGINT PRIMARY KEY,
|
||||||
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
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,
|
category_id BIGINT NOT NULL REFERENCES product.catalog_category(id) ON DELETE CASCADE,
|
||||||
CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id)
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
);
|
);
|
||||||
|
|
||||||
COMMENT ON TABLE product.product_category_bindings IS '商品类别/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系';
|
COMMENT ON TABLE product.product_catalog_bindings IS '商品目录分类/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系';
|
||||||
COMMENT ON COLUMN product.product_category_bindings.id IS '商品类别/分组绑定主键';
|
COMMENT ON COLUMN product.product_catalog_bindings.id IS '商品类别/分组绑定主键';
|
||||||
COMMENT ON COLUMN product.product_category_bindings.product_id IS '绑定商品 SPU ID,对应 product.products.id';
|
COMMENT ON COLUMN product.product_catalog_bindings.product_id IS '绑定商品 SPU ID,对应 product.products.id';
|
||||||
COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类/分组节点 ID,对应 product.product_category.id';
|
COMMENT ON COLUMN product.product_catalog_bindings.category_id IS '绑定分类/分组节点 ID,对应 product.catalog_category.id';
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id
|
CREATE INDEX IF NOT EXISTS idx_product_catalog_bindings_category_id
|
||||||
ON product.product_category_bindings (category_id);
|
ON product.product_catalog_bindings (category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_catalog_bindings_active_product_category
|
||||||
|
ON product.product_catalog_bindings (product_id, category_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_category (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
category_code VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
parent_id BIGINT REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
level SMALLINT NOT NULL CHECK (level BETWEEN 1 AND 4),
|
||||||
|
is_leaf BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
sort_num INTEGER NOT NULL DEFAULT 0,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
remark VARCHAR(500) NOT NULL DEFAULT '',
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_code_active
|
||||||
|
ON product.product_category (store_id, category_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_store_parent_name_active
|
||||||
|
ON product.product_category (store_id, COALESCE(parent_id, 0), lower(btrim(name))) WHERE deleted_at IS NULL;
|
||||||
|
CREATE TABLE IF NOT EXISTS product.product_category_bindings (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||||
|
product_category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE RESTRICT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_category_bindings_active
|
||||||
|
ON product.product_category_bindings (product_id, product_category_id) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_product
|
||||||
|
ON product.product_category_bindings (store_id, product_category_id, product_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS product.product_items (
|
CREATE TABLE IF NOT EXISTS product.product_items (
|
||||||
id BIGINT PRIMARY KEY,
|
id BIGINT PRIMARY KEY,
|
||||||
@ -167,6 +237,7 @@ CREATE TABLE IF NOT EXISTS product.product_items (
|
|||||||
sku_no VARCHAR(100),
|
sku_no VARCHAR(100),
|
||||||
name VARCHAR(256) NOT NULL,
|
name VARCHAR(256) NOT NULL,
|
||||||
price BIGINT NOT NULL CHECK (price >= 0),
|
price BIGINT NOT NULL CHECK (price >= 0),
|
||||||
|
supply_price BIGINT CONSTRAINT chk_product_items_supply_price CHECK (supply_price >= 0),
|
||||||
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||||
attributes JSONB NOT NULL DEFAULT '{}',
|
attributes JSONB NOT NULL DEFAULT '{}',
|
||||||
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
@ -182,6 +253,7 @@ CREATE TABLE IF NOT EXISTS product.product_items (
|
|||||||
|
|
||||||
COMMENT ON TABLE product.product_items IS '商品 SKU 明细表:存储具体可售规格、价格和规格属性;库存统一存储在 product.product_item_inventory';
|
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.price IS 'SKU 售价,单位:分';
|
||||||
|
COMMENT ON COLUMN product.product_items.supply_price IS 'SKU 供货价,单位:分;NULL 表示未维护';
|
||||||
COMMENT ON COLUMN product.product_items.image_ids IS 'SKU 图片 ID 列表';
|
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.attributes IS 'SKU 规格属性 JSONB,如颜色、尺寸等';
|
||||||
COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用';
|
COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用';
|
||||||
@ -198,9 +270,7 @@ CREATE INDEX IF NOT EXISTS idx_product_items_price
|
|||||||
ON product.product_items (price)
|
ON product.product_items (price)
|
||||||
WHERE deleted_at IS NULL;
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active
|
-- SKU business codes are not unique; use the SKU primary key for identity.
|
||||||
ON product.product_items (sku_no)
|
|
||||||
WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS product.product_item_inventory (
|
CREATE TABLE IF NOT EXISTS product.product_item_inventory (
|
||||||
id BIGINT PRIMARY KEY,
|
id BIGINT PRIMARY KEY,
|
||||||
@ -237,6 +307,49 @@ COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版
|
|||||||
COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存';
|
COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存';
|
||||||
COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定';
|
COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.suppliers (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
alias VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
supplier_code VARCHAR(64) NOT NULL,
|
||||||
|
attachments JSONB NOT NULL DEFAULT '[]'::JSONB,
|
||||||
|
contact_name VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
contact_phone VARCHAR(32) NOT NULL DEFAULT '',
|
||||||
|
remark VARCHAR(1000) NOT NULL DEFAULT '',
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_suppliers_store_code_active ON product.suppliers (store_id, supplier_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_suppliers_store_list ON product.suppliers (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS product.brands (
|
||||||
|
id BIGINT PRIMARY KEY,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
alias VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
brand_code VARCHAR(64) NOT NULL,
|
||||||
|
supplier_id BIGINT NOT NULL,
|
||||||
|
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
store_id BIGINT NOT NULL,
|
||||||
|
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_brands_store_code_active ON product.brands (store_id, brand_code) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_brands_store_list ON product.brands (store_id, created_at DESC, id DESC) WHERE deleted_at IS NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_brands_supplier ON product.brands (store_id, supplier_id) WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS set_suppliers_updated_at ON product.suppliers;
|
||||||
|
CREATE TRIGGER set_suppliers_updated_at BEFORE UPDATE ON product.suppliers FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
DROP TRIGGER IF EXISTS set_brands_updated_at ON product.brands;
|
||||||
|
CREATE TRIGGER set_brands_updated_at BEFORE UPDATE ON product.brands FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||||
|
|
||||||
DROP TRIGGER IF EXISTS set_products_updated_at ON product.products;
|
DROP TRIGGER IF EXISTS set_products_updated_at ON product.products;
|
||||||
CREATE TRIGGER set_products_updated_at
|
CREATE TRIGGER set_products_updated_at
|
||||||
BEFORE UPDATE ON product.products
|
BEFORE UPDATE ON product.products
|
||||||
@ -253,8 +366,12 @@ CREATE TRIGGER set_product_item_inventory_updated_at
|
|||||||
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
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.products TO svc_product;
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON product.catalog_category TO svc_product;
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_catalog_bindings TO svc_product;
|
||||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category 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_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_items TO svc_product;
|
||||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory 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;
|
GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product;
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON product.suppliers TO svc_product;
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON product.brands TO svc_product;
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user