diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..254929b --- /dev/null +++ b/.dockerignore @@ -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 diff --git a/.env.example b/.env.example index 1d7d2e1..ad00665 100644 --- a/.env.example +++ b/.env.example @@ -7,7 +7,6 @@ POSTGRES_DB=ids_ecommerce POSTGRES_SCHEMA=product POSTGRES_SSLMODE=disable NATS_URL=nats://localhost:4222 - METRICS_PORT=:9102 OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 OTEL_EXPORTER_OTLP_INSECURE=true diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..bd06e67 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -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}' + " diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..227c022 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/README.md b/README.md index 1e2b911..af31dd7 100644 --- a/README.md +++ b/README.md @@ -32,13 +32,15 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU | | `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 | | `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 | +| `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` 的商品分类,并按父子层级返回树 | ### `CreateProduct` 创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 -当前创建接口不再接收 `product_id`、`sku_id`、`inventory_id` 和 SKU `name`:`product_id`、`sku_id`、`inventory_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 +当前创建接口不接收 `product_id`、`sku_id`、`inventory_id`:这些 ID 均由商品服务应用层生成雪花 ID。SKU `name` 可显式传入;未传时由后端按规格值 `v1/v2/v3` 拼接。 创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成: @@ -48,24 +50,26 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` | | `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` | | 分类绑定 ID | 每个 `leaf_category_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` | +| 分组绑定 ID | 每个 `group_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` | 常用请求字段: | 字段 | 必填 | 说明 | |---|---:|---| -| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 | +| `spu_no` | 否 | 商品业务编码;空值可重复,非空值在当前店铺未删除商品中唯一 | | `title` | 是 | 商品标题 | | `selling_point` | 否 | 商品卖点 | | `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 | +| `group_ids` | 否 | 已存在的商品分组 ID 列表;传入后会写入全部商品分组绑定 | | `image_ids` | 否 | 商品图片 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` | | `freight_charge_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `freight_template_id` | | `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` | | `skus` | 否 | SKU 列表 | -`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。 +`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。`sku_no` 和 `name` 均可为空或重复,SKU 主键才是唯一标识。 最小示例: @@ -75,6 +79,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 "title": "澳洲和牛家庭装", "selling_point": "原切谷饲,冷链到家", "leaf_category_ids": ["726390485721088000"], + "group_ids": ["726390485721088001"], "skus": [ { "sku_no": "SKU20260710000101", @@ -118,7 +123,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 | | `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` | -返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。 +返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。该接口额外批量回填每个商品直接绑定的标准类目(含直属父节点和根至当前节点完整路径)、商品分组及当前可用品牌展示信息;无类目/分组时返回空数组,无品牌时返回空值。`ListCategoryProducts` 和 `SearchProducts` 不填充这些后台列表展示字段。 ### `ListCategoryProducts` @@ -127,7 +132,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `category_id` | `string` | 是 | 分类/分组节点 ID,对应 `product.product_category.id` | | `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 | | `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` | -| `only_visible` | `bool` | 否 | 为 `true` 时返回 `ON_SALE` 和 `OFF_SALE` 商品;小程序 BFF 固定传 `true`,Admin 不传以查看全部状态 | +| `only_visible` | `bool` | 否 | 为 `true` 时返回 `ON_SALE` 和 `SOLD_OUT` 商品;小程序 BFF 固定传 `true`,Admin 不传以查看全部状态 | 分页响应字段: @@ -139,11 +144,11 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 | `total` | `int64` | 分类/分组下商品总数 | | `total_pages` | `int32` | 总页数 | -`products[]` 返回商品摘要以及全部未归档 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。 +`products[]` 返回商品摘要以及全部未归档 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。状态 `3` 的消费者侧库存投影由 BFF 处理;商品服务仍保留真实账实。 ### `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` 渲染。 @@ -190,11 +195,34 @@ ids-svc-product/ ├── docs/ │ ├── ARCHITECTURE.md # 架构白皮书 │ └── DEVELOPMENT.md # 开发规约与 AI 生成指令 +├── Dockerfile # 生产镜像(需与 ids-proto 同级 context) ├── .env.example ├── go.mod └── 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: \ + . +``` + +**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 ``` -启动时会执行 `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) diff --git a/cmd/main.go b/cmd/main.go index b97fb8a..77a9647 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,14 +2,12 @@ package main import ( "context" - "database/sql" "net" "net/http" "os/signal" "syscall" "time" - _ "github.com/jackc/pgx/v5/stdlib" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.uber.org/zap" "go.uber.org/zap/zapcore" @@ -21,6 +19,7 @@ import ( 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/postgresutc" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" @@ -59,7 +58,7 @@ func main() { } }() - db, err := sql.Open("pgx", cfg.PostgresDSN) + db, err := postgresutc.Open(cfg.PostgresDSN) if err != nil { logger.Fatal("open postgres failed", zap.Error(err)) } @@ -73,6 +72,9 @@ func main() { } 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 { logger.Fatal("ensure product schema failed", zap.Error(err)) } @@ -87,15 +89,18 @@ func main() { }() productServer := server.NewProductServer(repo, idGenerator, logger, observer) + server.StartScheduledSaleWorker(ctx, repo, logger, time.Minute) grpcServer := grpc.NewServer( grpc.StatsHandler(otelgrpc.NewServerHandler()), grpc.UnaryInterceptor(observer.UnaryServerInterceptor()), ) productv1.RegisterProductServiceServer(grpcServer, productServer) + productv1.RegisterProductCategoryServiceServer(grpcServer, productServer) healthServer := health.NewServer() healthServer.SetServingStatus("", 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) healthpb.RegisterHealthServer(grpcServer, healthServer) reflection.Register(grpcServer) @@ -117,6 +122,7 @@ func main() { healthServer.SetServingStatus("", 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) grpcServer.GracefulStop() shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) @@ -128,6 +134,8 @@ func main() { func newLogger() (*zap.Logger, error) { 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() } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4ac31a5..52d16f1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -8,13 +8,14 @@ ## 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] - 本服务**仅允许**读写 PostgreSQL 中的 `product`。 - 绝对禁止跨 Schema 去 `JOIN` `trade`、`customer` 或任何其他业务 Schema 的表。 -- 任何关于订单状态、客户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。 +- 任何关于订单状态、客户会员权益、支付结果等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。 +- 商品表只保存 SKU 基础价、库存、`member_discount_enabled` 和运费事实;会员折扣率、积分规则、券和满减规则不得写入商品表。 ### 1.2 数据模型 (PostgreSQL) @@ -66,7 +67,7 @@ ## 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 @@ -83,6 +84,7 @@ 2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。 3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。 4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。 +5. **[ARC-PROD-008] 会员折扣边界:** 商品域只保存 `member_discount_enabled` 开关,不保存会员折扣率;折扣率由 `ids-svc-customer` 的会员快照提供,最终叠加由 `ids-svc-order` Quote 计算。 --- @@ -145,4 +147,5 @@ | ARC-PROD-004 | 价格字段统一 `int64`,单位为分 | | ARC-PROD-005 | 状态枚举强对齐 `productv1` proto 枚举 | | ARC-PROD-006 | 配置加载优先 `.env`,生产无 `.env` 时静默降级 | +| ARC-PROD-008 | 商品域只保存会员折扣开关,不保存折扣率 | | ADR-PROD-001 | 商品服务作为订单算价阶段的商品事实来源 | diff --git a/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md b/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md index 6b56fee..c9242e3 100644 --- a/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md +++ b/docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md @@ -20,8 +20,8 @@ | 数据库存储值 | Proto / API 枚举 | 含义 | 小程序行为 | |---:|---|---|---| | `1` | `PRODUCT_STATUS_INVENTORY` | 在仓库 | 不展示、不可购买 | -| `2` | `PRODUCT_STATUS_ON_SALE` | 已上架 | 展示、可购买 | -| `3` | `PRODUCT_STATUS_OFF_SALE` | 已售罄 | 展示已售罄状态、不可购买 | +| `2` | `PRODUCT_STATUS_ON_SALE` | 在销售 | 展示、可购买 | +| `3` | `PRODUCT_STATUS_SOLD_OUT` | 已售罄 | 展示已售罄状态、不可购买 | Proto 定义: @@ -29,7 +29,7 @@ Proto 定义: enum ProductStatus { PRODUCT_STATUS_INVENTORY = 1; PRODUCT_STATUS_ON_SALE = 2; - PRODUCT_STATUS_OFF_SALE = 3; + PRODUCT_STATUS_SOLD_OUT = 3; } ``` @@ -39,14 +39,14 @@ enum ProductStatus { INVENTORY -> ON_SALE 运营人员上架;至少存在一个可售 SKU。 -ON_SALE -> OFF_SALE - 所有当前可售 SKU 的 stock_quantity - locked_quantity <= 0 时系统自动下架, - 或由运营人员主动下架。 +ON_SALE -> SOLD_OUT + 所有当前可售 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 创建新的库存锁定; 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。 @@ -232,7 +232,7 @@ Content-Type: application/json { "product_id": "726390485721088003", "previous_status": "PRODUCT_STATUS_ON_SALE", - "status": "PRODUCT_STATUS_OFF_SALE", + "status": "PRODUCT_STATUS_SOLD_OUT", "version": 14, "updated_at": "1754388000000" } @@ -261,27 +261,17 @@ SKU 协议需要增加 `is_archived`、`archived_at` 与版本字段。普通接 |---:|---|---:|---| | `0` | DRAFT | `1` | INVENTORY | | `1` | ON_SALE | `2` | ON_SALE | -| `3` | OFF_SALE | `3` | OFF_SALE | +| `3` | SOLD_OUT | `3` | SOLD_OUT | | `2` | 当前无有效语义 | `1` | INVENTORY | 迁移后,`status` 默认值为 `1`,约束为 `status IN (1, 2, 3)`。 -SKU 编号唯一索引只约束当前有效 SKU: - -```sql -CREATE UNIQUE INDEX uq_product_items_sku_no_active -ON product.product_items (sku_no) -WHERE sku_no IS NOT NULL - AND deleted_at IS NULL - AND is_archived = FALSE; -``` - -必须先创建新索引,再删除旧 `uq_product_items_sku_no` 索引;否则归档 SKU 仍会阻止复用原 `sku_no`。 +SKU 编号不建立唯一索引。`sku_no` 和 SKU 名称均为业务展示字段,可在同一店铺的当前 SKU 中重复;所有库存、更新和订单关联均使用 SKU 主键。 ## 6. 实施位置 - `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` SQL 初始化、重建和正式迁移脚本:字段、约束和索引; - `ids-admin-api/internal/handler`、`internal/service`:两个 PATCH 路由、DTO、Mapper、版本冲突映射与图片 URL 解析; diff --git a/docs/admin-freight-template.md b/docs/admin-freight-template.md new file mode 100644 index 0000000..877bbac --- /dev/null +++ b/docs/admin-freight-template.md @@ -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` | diff --git a/internal/config/config.go b/internal/config/config.go index e75b906..ee32c3d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -44,7 +44,6 @@ func LoadConfig() (*Config, error) { if err != nil { return nil, err } - return &Config{ ServerPort: getEnv("SERVER_PORT", defaultServerPort), PostgresDSN: dsn, diff --git a/internal/freight/region.json b/internal/freight/region.json new file mode 100644 index 0000000..4998add --- /dev/null +++ b/internal/freight/region.json @@ -0,0 +1,15864 @@ +{ + "code": 0, + "msg": "", + "data": [ + { + "index": 0, + "part": "东北", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "和平区", + "regionId": 210102 + }, + { + "name": "沈河区", + "regionId": 210103 + }, + { + "name": "大东区", + "regionId": 210104 + }, + { + "name": "皇姑区", + "regionId": 210105 + }, + { + "name": "铁西区", + "regionId": 210106 + }, + { + "name": "苏家屯区", + "regionId": 210111 + }, + { + "name": "浑南区", + "regionId": 210112 + }, + { + "name": "沈北新区", + "regionId": 210113 + }, + { + "name": "于洪区", + "regionId": 210114 + }, + { + "name": "辽中区", + "regionId": 210115 + }, + { + "name": "康平县", + "regionId": 210123 + }, + { + "name": "法库县", + "regionId": 210124 + }, + { + "name": "新民市", + "regionId": 210181 + } + ], + "name": "沈阳市", + "regionId": 210100 + }, + { + "counties": [ + { + "name": "中山区", + "regionId": 210202 + }, + { + "name": "西岗区", + "regionId": 210203 + }, + { + "name": "沙河口区", + "regionId": 210204 + }, + { + "name": "甘井子区", + "regionId": 210211 + }, + { + "name": "旅顺口区", + "regionId": 210212 + }, + { + "name": "金州区", + "regionId": 210213 + }, + { + "name": "普兰店区", + "regionId": 210214 + }, + { + "name": "长海县", + "regionId": 210224 + }, + { + "name": "瓦房店市", + "regionId": 210281 + }, + { + "name": "庄河市", + "regionId": 210283 + } + ], + "name": "大连市", + "regionId": 210200 + }, + { + "counties": [ + { + "name": "铁东区", + "regionId": 210302 + }, + { + "name": "铁西区", + "regionId": 210303 + }, + { + "name": "立山区", + "regionId": 210304 + }, + { + "name": "千山区", + "regionId": 210311 + }, + { + "name": "台安县", + "regionId": 210321 + }, + { + "name": "岫岩满族自治县", + "regionId": 210323 + }, + { + "name": "海城市", + "regionId": 210381 + } + ], + "name": "鞍山市", + "regionId": 210300 + }, + { + "counties": [ + { + "name": "新抚区", + "regionId": 210402 + }, + { + "name": "东洲区", + "regionId": 210403 + }, + { + "name": "望花区", + "regionId": 210404 + }, + { + "name": "顺城区", + "regionId": 210411 + }, + { + "name": "抚顺县", + "regionId": 210421 + }, + { + "name": "新宾满族自治县", + "regionId": 210422 + }, + { + "name": "清原满族自治县", + "regionId": 210423 + } + ], + "name": "抚顺市", + "regionId": 210400 + }, + { + "counties": [ + { + "name": "平山区", + "regionId": 210502 + }, + { + "name": "溪湖区", + "regionId": 210503 + }, + { + "name": "明山区", + "regionId": 210504 + }, + { + "name": "南芬区", + "regionId": 210505 + }, + { + "name": "本溪满族自治县", + "regionId": 210521 + }, + { + "name": "桓仁满族自治县", + "regionId": 210522 + } + ], + "name": "本溪市", + "regionId": 210500 + }, + { + "counties": [ + { + "name": "元宝区", + "regionId": 210602 + }, + { + "name": "振兴区", + "regionId": 210603 + }, + { + "name": "振安区", + "regionId": 210604 + }, + { + "name": "宽甸满族自治县", + "regionId": 210624 + }, + { + "name": "东港市", + "regionId": 210681 + }, + { + "name": "凤城市", + "regionId": 210682 + } + ], + "name": "丹东市", + "regionId": 210600 + }, + { + "counties": [ + { + "name": "古塔区", + "regionId": 210702 + }, + { + "name": "凌河区", + "regionId": 210703 + }, + { + "name": "太和区", + "regionId": 210711 + }, + { + "name": "黑山县", + "regionId": 210726 + }, + { + "name": "义县", + "regionId": 210727 + }, + { + "name": "凌海市", + "regionId": 210781 + }, + { + "name": "北镇市", + "regionId": 210782 + } + ], + "name": "锦州市", + "regionId": 210700 + }, + { + "counties": [ + { + "name": "站前区", + "regionId": 210802 + }, + { + "name": "西市区", + "regionId": 210803 + }, + { + "name": "鲅鱼圈区", + "regionId": 210804 + }, + { + "name": "老边区", + "regionId": 210811 + }, + { + "name": "盖州市", + "regionId": 210881 + }, + { + "name": "大石桥市", + "regionId": 210882 + } + ], + "name": "营口市", + "regionId": 210800 + }, + { + "counties": [ + { + "name": "海州区", + "regionId": 210902 + }, + { + "name": "新邱区", + "regionId": 210903 + }, + { + "name": "太平区", + "regionId": 210904 + }, + { + "name": "清河门区", + "regionId": 210905 + }, + { + "name": "细河区", + "regionId": 210911 + }, + { + "name": "阜新蒙古族自治县", + "regionId": 210921 + }, + { + "name": "彰武县", + "regionId": 210922 + } + ], + "name": "阜新市", + "regionId": 210900 + }, + { + "counties": [ + { + "name": "白塔区", + "regionId": 211002 + }, + { + "name": "文圣区", + "regionId": 211003 + }, + { + "name": "宏伟区", + "regionId": 211004 + }, + { + "name": "弓长岭区", + "regionId": 211005 + }, + { + "name": "太子河区", + "regionId": 211011 + }, + { + "name": "辽阳县", + "regionId": 211021 + }, + { + "name": "灯塔市", + "regionId": 211081 + } + ], + "name": "辽阳市", + "regionId": 211000 + }, + { + "counties": [ + { + "name": "双台子区", + "regionId": 211102 + }, + { + "name": "兴隆台区", + "regionId": 211103 + }, + { + "name": "大洼区", + "regionId": 211104 + }, + { + "name": "盘山县", + "regionId": 211122 + } + ], + "name": "盘锦市", + "regionId": 211100 + }, + { + "counties": [ + { + "name": "银州区", + "regionId": 211202 + }, + { + "name": "清河区", + "regionId": 211204 + }, + { + "name": "铁岭县", + "regionId": 211221 + }, + { + "name": "西丰县", + "regionId": 211223 + }, + { + "name": "昌图县", + "regionId": 211224 + }, + { + "name": "调兵山市", + "regionId": 211281 + }, + { + "name": "开原市", + "regionId": 211282 + } + ], + "name": "铁岭市", + "regionId": 211200 + }, + { + "counties": [ + { + "name": "双塔区", + "regionId": 211302 + }, + { + "name": "龙城区", + "regionId": 211303 + }, + { + "name": "朝阳县", + "regionId": 211321 + }, + { + "name": "建平县", + "regionId": 211322 + }, + { + "name": "喀喇沁左翼蒙古族自治县", + "regionId": 211324 + }, + { + "name": "北票市", + "regionId": 211381 + }, + { + "name": "凌源市", + "regionId": 211382 + } + ], + "name": "朝阳市", + "regionId": 211300 + }, + { + "counties": [ + { + "name": "连山区", + "regionId": 211402 + }, + { + "name": "龙港区", + "regionId": 211403 + }, + { + "name": "南票区", + "regionId": 211404 + }, + { + "name": "绥中县", + "regionId": 211421 + }, + { + "name": "建昌县", + "regionId": 211422 + }, + { + "name": "兴城市", + "regionId": 211481 + } + ], + "name": "葫芦岛市", + "regionId": 211400 + } + ], + "name": "辽宁省", + "regionId": 210000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "南关区", + "regionId": 220102 + }, + { + "name": "宽城区", + "regionId": 220103 + }, + { + "name": "朝阳区", + "regionId": 220104 + }, + { + "name": "二道区", + "regionId": 220105 + }, + { + "name": "绿园区", + "regionId": 220106 + }, + { + "name": "双阳区", + "regionId": 220112 + }, + { + "name": "九台区", + "regionId": 220113 + }, + { + "name": "农安县", + "regionId": 220122 + }, + { + "name": "榆树市", + "regionId": 220182 + }, + { + "name": "德惠市", + "regionId": 220183 + }, + { + "name": "公主岭市", + "regionId": 220184 + } + ], + "name": "长春市", + "regionId": 220100 + }, + { + "counties": [ + { + "name": "昌邑区", + "regionId": 220202 + }, + { + "name": "龙潭区", + "regionId": 220203 + }, + { + "name": "船营区", + "regionId": 220204 + }, + { + "name": "丰满区", + "regionId": 220211 + }, + { + "name": "永吉县", + "regionId": 220221 + }, + { + "name": "蛟河市", + "regionId": 220281 + }, + { + "name": "桦甸市", + "regionId": 220282 + }, + { + "name": "舒兰市", + "regionId": 220283 + }, + { + "name": "磐石市", + "regionId": 220284 + } + ], + "name": "吉林市", + "regionId": 220200 + }, + { + "counties": [ + { + "name": "铁西区", + "regionId": 220302 + }, + { + "name": "铁东区", + "regionId": 220303 + }, + { + "name": "梨树县", + "regionId": 220322 + }, + { + "name": "伊通满族自治县", + "regionId": 220323 + }, + { + "name": "双辽市", + "regionId": 220382 + } + ], + "name": "四平市", + "regionId": 220300 + }, + { + "counties": [ + { + "name": "龙山区", + "regionId": 220402 + }, + { + "name": "西安区", + "regionId": 220403 + }, + { + "name": "东丰县", + "regionId": 220421 + }, + { + "name": "东辽县", + "regionId": 220422 + } + ], + "name": "辽源市", + "regionId": 220400 + }, + { + "counties": [ + { + "name": "东昌区", + "regionId": 220502 + }, + { + "name": "二道江区", + "regionId": 220503 + }, + { + "name": "通化县", + "regionId": 220521 + }, + { + "name": "辉南县", + "regionId": 220523 + }, + { + "name": "柳河县", + "regionId": 220524 + }, + { + "name": "梅河口市", + "regionId": 220581 + }, + { + "name": "集安市", + "regionId": 220582 + } + ], + "name": "通化市", + "regionId": 220500 + }, + { + "counties": [ + { + "name": "浑江区", + "regionId": 220602 + }, + { + "name": "江源区", + "regionId": 220605 + }, + { + "name": "抚松县", + "regionId": 220621 + }, + { + "name": "靖宇县", + "regionId": 220622 + }, + { + "name": "长白朝鲜族自治县", + "regionId": 220623 + }, + { + "name": "临江市", + "regionId": 220681 + } + ], + "name": "白山市", + "regionId": 220600 + }, + { + "counties": [ + { + "name": "宁江区", + "regionId": 220702 + }, + { + "name": "前郭尔罗斯蒙古族自治县", + "regionId": 220721 + }, + { + "name": "长岭县", + "regionId": 220722 + }, + { + "name": "乾安县", + "regionId": 220723 + }, + { + "name": "扶余市", + "regionId": 220781 + } + ], + "name": "松原市", + "regionId": 220700 + }, + { + "counties": [ + { + "name": "洮北区", + "regionId": 220802 + }, + { + "name": "镇赉县", + "regionId": 220821 + }, + { + "name": "通榆县", + "regionId": 220822 + }, + { + "name": "洮南市", + "regionId": 220881 + }, + { + "name": "大安市", + "regionId": 220882 + } + ], + "name": "白城市", + "regionId": 220800 + }, + { + "counties": [ + { + "name": "延吉市", + "regionId": 222401 + }, + { + "name": "图们市", + "regionId": 222402 + }, + { + "name": "敦化市", + "regionId": 222403 + }, + { + "name": "珲春市", + "regionId": 222404 + }, + { + "name": "龙井市", + "regionId": 222405 + }, + { + "name": "和龙市", + "regionId": 222406 + }, + { + "name": "汪清县", + "regionId": 222424 + }, + { + "name": "安图县", + "regionId": 222426 + } + ], + "name": "延边朝鲜族自治州", + "regionId": 222400 + } + ], + "name": "吉林省", + "regionId": 220000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "道里区", + "regionId": 230102 + }, + { + "name": "南岗区", + "regionId": 230103 + }, + { + "name": "道外区", + "regionId": 230104 + }, + { + "name": "平房区", + "regionId": 230108 + }, + { + "name": "松北区", + "regionId": 230109 + }, + { + "name": "香坊区", + "regionId": 230110 + }, + { + "name": "呼兰区", + "regionId": 230111 + }, + { + "name": "阿城区", + "regionId": 230112 + }, + { + "name": "双城区", + "regionId": 230113 + }, + { + "name": "依兰县", + "regionId": 230123 + }, + { + "name": "方正县", + "regionId": 230124 + }, + { + "name": "宾县", + "regionId": 230125 + }, + { + "name": "巴彦县", + "regionId": 230126 + }, + { + "name": "木兰县", + "regionId": 230127 + }, + { + "name": "通河县", + "regionId": 230128 + }, + { + "name": "延寿县", + "regionId": 230129 + }, + { + "name": "尚志市", + "regionId": 230183 + }, + { + "name": "五常市", + "regionId": 230184 + } + ], + "name": "哈尔滨市", + "regionId": 230100 + }, + { + "counties": [ + { + "name": "龙沙区", + "regionId": 230202 + }, + { + "name": "建华区", + "regionId": 230203 + }, + { + "name": "铁锋区", + "regionId": 230204 + }, + { + "name": "昂昂溪区", + "regionId": 230205 + }, + { + "name": "富拉尔基区", + "regionId": 230206 + }, + { + "name": "碾子山区", + "regionId": 230207 + }, + { + "name": "梅里斯达斡尔族区", + "regionId": 230208 + }, + { + "name": "龙江县", + "regionId": 230221 + }, + { + "name": "依安县", + "regionId": 230223 + }, + { + "name": "泰来县", + "regionId": 230224 + }, + { + "name": "甘南县", + "regionId": 230225 + }, + { + "name": "富裕县", + "regionId": 230227 + }, + { + "name": "克山县", + "regionId": 230229 + }, + { + "name": "克东县", + "regionId": 230230 + }, + { + "name": "拜泉县", + "regionId": 230231 + }, + { + "name": "讷河市", + "regionId": 230281 + } + ], + "name": "齐齐哈尔市", + "regionId": 230200 + }, + { + "counties": [ + { + "name": "鸡冠区", + "regionId": 230302 + }, + { + "name": "恒山区", + "regionId": 230303 + }, + { + "name": "滴道区", + "regionId": 230304 + }, + { + "name": "梨树区", + "regionId": 230305 + }, + { + "name": "城子河区", + "regionId": 230306 + }, + { + "name": "麻山区", + "regionId": 230307 + }, + { + "name": "鸡东县", + "regionId": 230321 + }, + { + "name": "虎林市", + "regionId": 230381 + }, + { + "name": "密山市", + "regionId": 230382 + } + ], + "name": "鸡西市", + "regionId": 230300 + }, + { + "counties": [ + { + "name": "向阳区", + "regionId": 230402 + }, + { + "name": "工农区", + "regionId": 230403 + }, + { + "name": "南山区", + "regionId": 230404 + }, + { + "name": "兴安区", + "regionId": 230405 + }, + { + "name": "东山区", + "regionId": 230406 + }, + { + "name": "兴山区", + "regionId": 230407 + }, + { + "name": "萝北县", + "regionId": 230421 + }, + { + "name": "绥滨县", + "regionId": 230422 + } + ], + "name": "鹤岗市", + "regionId": 230400 + }, + { + "counties": [ + { + "name": "尖山区", + "regionId": 230502 + }, + { + "name": "岭东区", + "regionId": 230503 + }, + { + "name": "四方台区", + "regionId": 230505 + }, + { + "name": "宝山区", + "regionId": 230506 + }, + { + "name": "集贤县", + "regionId": 230521 + }, + { + "name": "友谊县", + "regionId": 230522 + }, + { + "name": "宝清县", + "regionId": 230523 + }, + { + "name": "饶河县", + "regionId": 230524 + } + ], + "name": "双鸭山市", + "regionId": 230500 + }, + { + "counties": [ + { + "name": "萨尔图区", + "regionId": 230602 + }, + { + "name": "龙凤区", + "regionId": 230603 + }, + { + "name": "让胡路区", + "regionId": 230604 + }, + { + "name": "红岗区", + "regionId": 230605 + }, + { + "name": "大同区", + "regionId": 230606 + }, + { + "name": "肇州县", + "regionId": 230621 + }, + { + "name": "肇源县", + "regionId": 230622 + }, + { + "name": "林甸县", + "regionId": 230623 + }, + { + "name": "杜尔伯特蒙古族自治县", + "regionId": 230624 + } + ], + "name": "大庆市", + "regionId": 230600 + }, + { + "counties": [ + { + "name": "伊美区", + "regionId": 230717 + }, + { + "name": "乌翠区", + "regionId": 230718 + }, + { + "name": "友好区", + "regionId": 230719 + }, + { + "name": "嘉荫县", + "regionId": 230722 + }, + { + "name": "汤旺县", + "regionId": 230723 + }, + { + "name": "丰林县", + "regionId": 230724 + }, + { + "name": "大箐山县", + "regionId": 230725 + }, + { + "name": "南岔县", + "regionId": 230726 + }, + { + "name": "金林区", + "regionId": 230751 + }, + { + "name": "铁力市", + "regionId": 230781 + } + ], + "name": "伊春市", + "regionId": 230700 + }, + { + "counties": [ + { + "name": "向阳区", + "regionId": 230803 + }, + { + "name": "前进区", + "regionId": 230804 + }, + { + "name": "东风区", + "regionId": 230805 + }, + { + "name": "郊区", + "regionId": 230811 + }, + { + "name": "桦南县", + "regionId": 230822 + }, + { + "name": "桦川县", + "regionId": 230826 + }, + { + "name": "汤原县", + "regionId": 230828 + }, + { + "name": "同江市", + "regionId": 230881 + }, + { + "name": "富锦市", + "regionId": 230882 + }, + { + "name": "抚远市", + "regionId": 230883 + } + ], + "name": "佳木斯市", + "regionId": 230800 + }, + { + "counties": [ + { + "name": "新兴区", + "regionId": 230902 + }, + { + "name": "桃山区", + "regionId": 230903 + }, + { + "name": "茄子河区", + "regionId": 230904 + }, + { + "name": "勃利县", + "regionId": 230921 + } + ], + "name": "七台河市", + "regionId": 230900 + }, + { + "counties": [ + { + "name": "东安区", + "regionId": 231002 + }, + { + "name": "阳明区", + "regionId": 231003 + }, + { + "name": "爱民区", + "regionId": 231004 + }, + { + "name": "西安区", + "regionId": 231005 + }, + { + "name": "林口县", + "regionId": 231025 + }, + { + "name": "绥芬河市", + "regionId": 231081 + }, + { + "name": "海林市", + "regionId": 231083 + }, + { + "name": "宁安市", + "regionId": 231084 + }, + { + "name": "穆棱市", + "regionId": 231085 + }, + { + "name": "东宁市", + "regionId": 231086 + } + ], + "name": "牡丹江市", + "regionId": 231000 + }, + { + "counties": [ + { + "name": "爱辉区", + "regionId": 231102 + }, + { + "name": "逊克县", + "regionId": 231123 + }, + { + "name": "孙吴县", + "regionId": 231124 + }, + { + "name": "北安市", + "regionId": 231181 + }, + { + "name": "五大连池市", + "regionId": 231182 + }, + { + "name": "嫩江市", + "regionId": 231183 + } + ], + "name": "黑河市", + "regionId": 231100 + }, + { + "counties": [ + { + "name": "北林区", + "regionId": 231202 + }, + { + "name": "望奎县", + "regionId": 231221 + }, + { + "name": "兰西县", + "regionId": 231222 + }, + { + "name": "青冈县", + "regionId": 231223 + }, + { + "name": "庆安县", + "regionId": 231224 + }, + { + "name": "明水县", + "regionId": 231225 + }, + { + "name": "绥棱县", + "regionId": 231226 + }, + { + "name": "安达市", + "regionId": 231281 + }, + { + "name": "肇东市", + "regionId": 231282 + }, + { + "name": "海伦市", + "regionId": 231283 + } + ], + "name": "绥化市", + "regionId": 231200 + }, + { + "counties": [ + { + "name": "漠河市", + "regionId": 232701 + }, + { + "name": "呼玛县", + "regionId": 232721 + }, + { + "name": "塔河县", + "regionId": 232722 + }, + { + "name": "加格达奇区", + "regionId": 232792 + } + ], + "name": "大兴安岭地区", + "regionId": 232700 + } + ], + "name": "黑龙江省", + "regionId": 230000 + } + ] + }, + { + "index": 1, + "part": "华东", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "黄浦区", + "regionId": 310101 + }, + { + "name": "徐汇区", + "regionId": 310104 + }, + { + "name": "长宁区", + "regionId": 310105 + }, + { + "name": "静安区", + "regionId": 310106 + }, + { + "name": "普陀区", + "regionId": 310107 + }, + { + "name": "虹口区", + "regionId": 310109 + }, + { + "name": "杨浦区", + "regionId": 310110 + }, + { + "name": "闵行区", + "regionId": 310112 + }, + { + "name": "宝山区", + "regionId": 310113 + }, + { + "name": "嘉定区", + "regionId": 310114 + }, + { + "name": "浦东新区", + "regionId": 310115 + }, + { + "name": "金山区", + "regionId": 310116 + }, + { + "name": "松江区", + "regionId": 310117 + }, + { + "name": "青浦区", + "regionId": 310118 + }, + { + "name": "奉贤区", + "regionId": 310120 + }, + { + "name": "崇明区", + "regionId": 310151 + } + ], + "name": "上海市", + "regionId": 310100 + } + ], + "name": "上海市", + "regionId": 310000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "玄武区", + "regionId": 320102 + }, + { + "name": "秦淮区", + "regionId": 320104 + }, + { + "name": "建邺区", + "regionId": 320105 + }, + { + "name": "鼓楼区", + "regionId": 320106 + }, + { + "name": "浦口区", + "regionId": 320111 + }, + { + "name": "栖霞区", + "regionId": 320113 + }, + { + "name": "雨花台区", + "regionId": 320114 + }, + { + "name": "江宁区", + "regionId": 320115 + }, + { + "name": "六合区", + "regionId": 320116 + }, + { + "name": "溧水区", + "regionId": 320117 + }, + { + "name": "高淳区", + "regionId": 320118 + } + ], + "name": "南京市", + "regionId": 320100 + }, + { + "counties": [ + { + "name": "锡山区", + "regionId": 320205 + }, + { + "name": "惠山区", + "regionId": 320206 + }, + { + "name": "滨湖区", + "regionId": 320211 + }, + { + "name": "梁溪区", + "regionId": 320213 + }, + { + "name": "新吴区", + "regionId": 320214 + }, + { + "name": "江阴市", + "regionId": 320281 + }, + { + "name": "宜兴市", + "regionId": 320282 + } + ], + "name": "无锡市", + "regionId": 320200 + }, + { + "counties": [ + { + "name": "鼓楼区", + "regionId": 320302 + }, + { + "name": "云龙区", + "regionId": 320303 + }, + { + "name": "贾汪区", + "regionId": 320305 + }, + { + "name": "泉山区", + "regionId": 320311 + }, + { + "name": "铜山区", + "regionId": 320312 + }, + { + "name": "丰县", + "regionId": 320321 + }, + { + "name": "沛县", + "regionId": 320322 + }, + { + "name": "睢宁县", + "regionId": 320324 + }, + { + "name": "新沂市", + "regionId": 320381 + }, + { + "name": "邳州市", + "regionId": 320382 + } + ], + "name": "徐州市", + "regionId": 320300 + }, + { + "counties": [ + { + "name": "天宁区", + "regionId": 320402 + }, + { + "name": "钟楼区", + "regionId": 320404 + }, + { + "name": "新北区", + "regionId": 320411 + }, + { + "name": "武进区", + "regionId": 320412 + }, + { + "name": "金坛区", + "regionId": 320413 + }, + { + "name": "溧阳市", + "regionId": 320481 + } + ], + "name": "常州市", + "regionId": 320400 + }, + { + "counties": [ + { + "name": "虎丘区", + "regionId": 320505 + }, + { + "name": "吴中区", + "regionId": 320506 + }, + { + "name": "相城区", + "regionId": 320507 + }, + { + "name": "姑苏区", + "regionId": 320508 + }, + { + "name": "吴江区", + "regionId": 320509 + }, + { + "name": "常熟市", + "regionId": 320581 + }, + { + "name": "张家港市", + "regionId": 320582 + }, + { + "name": "昆山市", + "regionId": 320583 + }, + { + "name": "太仓市", + "regionId": 320585 + } + ], + "name": "苏州市", + "regionId": 320500 + }, + { + "counties": [ + { + "name": "通州区", + "regionId": 320612 + }, + { + "name": "崇川区", + "regionId": 320613 + }, + { + "name": "海门区", + "regionId": 320614 + }, + { + "name": "如东县", + "regionId": 320623 + }, + { + "name": "启东市", + "regionId": 320681 + }, + { + "name": "如皋市", + "regionId": 320682 + }, + { + "name": "海安市", + "regionId": 320685 + } + ], + "name": "南通市", + "regionId": 320600 + }, + { + "counties": [ + { + "name": "连云区", + "regionId": 320703 + }, + { + "name": "海州区", + "regionId": 320706 + }, + { + "name": "赣榆区", + "regionId": 320707 + }, + { + "name": "东海县", + "regionId": 320722 + }, + { + "name": "灌云县", + "regionId": 320723 + }, + { + "name": "灌南县", + "regionId": 320724 + } + ], + "name": "连云港市", + "regionId": 320700 + }, + { + "counties": [ + { + "name": "淮安区", + "regionId": 320803 + }, + { + "name": "淮阴区", + "regionId": 320804 + }, + { + "name": "清江浦区", + "regionId": 320812 + }, + { + "name": "洪泽区", + "regionId": 320813 + }, + { + "name": "涟水县", + "regionId": 320826 + }, + { + "name": "盱眙县", + "regionId": 320830 + }, + { + "name": "金湖县", + "regionId": 320831 + } + ], + "name": "淮安市", + "regionId": 320800 + }, + { + "counties": [ + { + "name": "亭湖区", + "regionId": 320902 + }, + { + "name": "盐都区", + "regionId": 320903 + }, + { + "name": "大丰区", + "regionId": 320904 + }, + { + "name": "响水县", + "regionId": 320921 + }, + { + "name": "滨海县", + "regionId": 320922 + }, + { + "name": "阜宁县", + "regionId": 320923 + }, + { + "name": "射阳县", + "regionId": 320924 + }, + { + "name": "建湖县", + "regionId": 320925 + }, + { + "name": "东台市", + "regionId": 320981 + } + ], + "name": "盐城市", + "regionId": 320900 + }, + { + "counties": [ + { + "name": "广陵区", + "regionId": 321002 + }, + { + "name": "邗江区", + "regionId": 321003 + }, + { + "name": "江都区", + "regionId": 321012 + }, + { + "name": "宝应县", + "regionId": 321023 + }, + { + "name": "仪征市", + "regionId": 321081 + }, + { + "name": "高邮市", + "regionId": 321084 + } + ], + "name": "扬州市", + "regionId": 321000 + }, + { + "counties": [ + { + "name": "京口区", + "regionId": 321102 + }, + { + "name": "润州区", + "regionId": 321111 + }, + { + "name": "丹徒区", + "regionId": 321112 + }, + { + "name": "丹阳市", + "regionId": 321181 + }, + { + "name": "扬中市", + "regionId": 321182 + }, + { + "name": "句容市", + "regionId": 321183 + } + ], + "name": "镇江市", + "regionId": 321100 + }, + { + "counties": [ + { + "name": "海陵区", + "regionId": 321202 + }, + { + "name": "高港区", + "regionId": 321203 + }, + { + "name": "姜堰区", + "regionId": 321204 + }, + { + "name": "兴化市", + "regionId": 321281 + }, + { + "name": "靖江市", + "regionId": 321282 + }, + { + "name": "泰兴市", + "regionId": 321283 + } + ], + "name": "泰州市", + "regionId": 321200 + }, + { + "counties": [ + { + "name": "宿城区", + "regionId": 321302 + }, + { + "name": "宿豫区", + "regionId": 321311 + }, + { + "name": "沭阳县", + "regionId": 321322 + }, + { + "name": "泗阳县", + "regionId": 321323 + }, + { + "name": "泗洪县", + "regionId": 321324 + } + ], + "name": "宿迁市", + "regionId": 321300 + } + ], + "name": "江苏省", + "regionId": 320000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "上城区", + "regionId": 330102 + }, + { + "name": "拱墅区", + "regionId": 330105 + }, + { + "name": "西湖区", + "regionId": 330106 + }, + { + "name": "滨江区", + "regionId": 330108 + }, + { + "name": "萧山区", + "regionId": 330109 + }, + { + "name": "余杭区", + "regionId": 330110 + }, + { + "name": "富阳区", + "regionId": 330111 + }, + { + "name": "临安区", + "regionId": 330112 + }, + { + "name": "临平区", + "regionId": 330113 + }, + { + "name": "钱塘区", + "regionId": 330114 + }, + { + "name": "桐庐县", + "regionId": 330122 + }, + { + "name": "淳安县", + "regionId": 330127 + }, + { + "name": "建德市", + "regionId": 330182 + } + ], + "name": "杭州市", + "regionId": 330100 + }, + { + "counties": [ + { + "name": "海曙区", + "regionId": 330203 + }, + { + "name": "江北区", + "regionId": 330205 + }, + { + "name": "北仑区", + "regionId": 330206 + }, + { + "name": "镇海区", + "regionId": 330211 + }, + { + "name": "鄞州区", + "regionId": 330212 + }, + { + "name": "奉化区", + "regionId": 330213 + }, + { + "name": "象山县", + "regionId": 330225 + }, + { + "name": "宁海县", + "regionId": 330226 + }, + { + "name": "余姚市", + "regionId": 330281 + }, + { + "name": "慈溪市", + "regionId": 330282 + } + ], + "name": "宁波市", + "regionId": 330200 + }, + { + "counties": [ + { + "name": "鹿城区", + "regionId": 330302 + }, + { + "name": "龙湾区", + "regionId": 330303 + }, + { + "name": "瓯海区", + "regionId": 330304 + }, + { + "name": "洞头区", + "regionId": 330305 + }, + { + "name": "永嘉县", + "regionId": 330324 + }, + { + "name": "平阳县", + "regionId": 330326 + }, + { + "name": "苍南县", + "regionId": 330327 + }, + { + "name": "文成县", + "regionId": 330328 + }, + { + "name": "泰顺县", + "regionId": 330329 + }, + { + "name": "瑞安市", + "regionId": 330381 + }, + { + "name": "乐清市", + "regionId": 330382 + }, + { + "name": "龙港市", + "regionId": 330383 + } + ], + "name": "温州市", + "regionId": 330300 + }, + { + "counties": [ + { + "name": "南湖区", + "regionId": 330402 + }, + { + "name": "秀洲区", + "regionId": 330411 + }, + { + "name": "嘉善县", + "regionId": 330421 + }, + { + "name": "海盐县", + "regionId": 330424 + }, + { + "name": "海宁市", + "regionId": 330481 + }, + { + "name": "平湖市", + "regionId": 330482 + }, + { + "name": "桐乡市", + "regionId": 330483 + } + ], + "name": "嘉兴市", + "regionId": 330400 + }, + { + "counties": [ + { + "name": "吴兴区", + "regionId": 330502 + }, + { + "name": "南浔区", + "regionId": 330503 + }, + { + "name": "德清县", + "regionId": 330521 + }, + { + "name": "长兴县", + "regionId": 330522 + }, + { + "name": "安吉县", + "regionId": 330523 + } + ], + "name": "湖州市", + "regionId": 330500 + }, + { + "counties": [ + { + "name": "越城区", + "regionId": 330602 + }, + { + "name": "柯桥区", + "regionId": 330603 + }, + { + "name": "上虞区", + "regionId": 330604 + }, + { + "name": "新昌县", + "regionId": 330624 + }, + { + "name": "诸暨市", + "regionId": 330681 + }, + { + "name": "嵊州市", + "regionId": 330683 + } + ], + "name": "绍兴市", + "regionId": 330600 + }, + { + "counties": [ + { + "name": "婺城区", + "regionId": 330702 + }, + { + "name": "金东区", + "regionId": 330703 + }, + { + "name": "武义县", + "regionId": 330723 + }, + { + "name": "浦江县", + "regionId": 330726 + }, + { + "name": "磐安县", + "regionId": 330727 + }, + { + "name": "兰溪市", + "regionId": 330781 + }, + { + "name": "义乌市", + "regionId": 330782 + }, + { + "name": "东阳市", + "regionId": 330783 + }, + { + "name": "永康市", + "regionId": 330784 + } + ], + "name": "金华市", + "regionId": 330700 + }, + { + "counties": [ + { + "name": "柯城区", + "regionId": 330802 + }, + { + "name": "衢江区", + "regionId": 330803 + }, + { + "name": "常山县", + "regionId": 330822 + }, + { + "name": "开化县", + "regionId": 330824 + }, + { + "name": "龙游县", + "regionId": 330825 + }, + { + "name": "江山市", + "regionId": 330881 + } + ], + "name": "衢州市", + "regionId": 330800 + }, + { + "counties": [ + { + "name": "定海区", + "regionId": 330902 + }, + { + "name": "普陀区", + "regionId": 330903 + }, + { + "name": "岱山县", + "regionId": 330921 + }, + { + "name": "嵊泗县", + "regionId": 330922 + } + ], + "name": "舟山市", + "regionId": 330900 + }, + { + "counties": [ + { + "name": "椒江区", + "regionId": 331002 + }, + { + "name": "黄岩区", + "regionId": 331003 + }, + { + "name": "路桥区", + "regionId": 331004 + }, + { + "name": "三门县", + "regionId": 331022 + }, + { + "name": "天台县", + "regionId": 331023 + }, + { + "name": "仙居县", + "regionId": 331024 + }, + { + "name": "温岭市", + "regionId": 331081 + }, + { + "name": "临海市", + "regionId": 331082 + }, + { + "name": "玉环市", + "regionId": 331083 + } + ], + "name": "台州市", + "regionId": 331000 + }, + { + "counties": [ + { + "name": "莲都区", + "regionId": 331102 + }, + { + "name": "青田县", + "regionId": 331121 + }, + { + "name": "缙云县", + "regionId": 331122 + }, + { + "name": "遂昌县", + "regionId": 331123 + }, + { + "name": "松阳县", + "regionId": 331124 + }, + { + "name": "云和县", + "regionId": 331125 + }, + { + "name": "庆元县", + "regionId": 331126 + }, + { + "name": "景宁畲族自治县", + "regionId": 331127 + }, + { + "name": "龙泉市", + "regionId": 331181 + } + ], + "name": "丽水市", + "regionId": 331100 + } + ], + "name": "浙江省", + "regionId": 330000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "瑶海区", + "regionId": 340102 + }, + { + "name": "庐阳区", + "regionId": 340103 + }, + { + "name": "蜀山区", + "regionId": 340104 + }, + { + "name": "包河区", + "regionId": 340111 + }, + { + "name": "长丰县", + "regionId": 340121 + }, + { + "name": "肥东县", + "regionId": 340122 + }, + { + "name": "肥西县", + "regionId": 340123 + }, + { + "name": "庐江县", + "regionId": 340124 + }, + { + "name": "巢湖市", + "regionId": 340181 + } + ], + "name": "合肥市", + "regionId": 340100 + }, + { + "counties": [ + { + "name": "镜湖区", + "regionId": 340202 + }, + { + "name": "鸠江区", + "regionId": 340207 + }, + { + "name": "弋江区", + "regionId": 340209 + }, + { + "name": "湾沚区", + "regionId": 340210 + }, + { + "name": "繁昌区", + "regionId": 340212 + }, + { + "name": "南陵县", + "regionId": 340223 + }, + { + "name": "无为市", + "regionId": 340281 + } + ], + "name": "芜湖市", + "regionId": 340200 + }, + { + "counties": [ + { + "name": "龙子湖区", + "regionId": 340302 + }, + { + "name": "蚌山区", + "regionId": 340303 + }, + { + "name": "禹会区", + "regionId": 340304 + }, + { + "name": "淮上区", + "regionId": 340311 + }, + { + "name": "怀远县", + "regionId": 340321 + }, + { + "name": "五河县", + "regionId": 340322 + }, + { + "name": "固镇县", + "regionId": 340323 + } + ], + "name": "蚌埠市", + "regionId": 340300 + }, + { + "counties": [ + { + "name": "大通区", + "regionId": 340402 + }, + { + "name": "田家庵区", + "regionId": 340403 + }, + { + "name": "谢家集区", + "regionId": 340404 + }, + { + "name": "八公山区", + "regionId": 340405 + }, + { + "name": "潘集区", + "regionId": 340406 + }, + { + "name": "凤台县", + "regionId": 340421 + }, + { + "name": "寿县", + "regionId": 340422 + } + ], + "name": "淮南市", + "regionId": 340400 + }, + { + "counties": [ + { + "name": "花山区", + "regionId": 340503 + }, + { + "name": "雨山区", + "regionId": 340504 + }, + { + "name": "博望区", + "regionId": 340506 + }, + { + "name": "当涂县", + "regionId": 340521 + }, + { + "name": "含山县", + "regionId": 340522 + }, + { + "name": "和县", + "regionId": 340523 + } + ], + "name": "马鞍山市", + "regionId": 340500 + }, + { + "counties": [ + { + "name": "杜集区", + "regionId": 340602 + }, + { + "name": "相山区", + "regionId": 340603 + }, + { + "name": "烈山区", + "regionId": 340604 + }, + { + "name": "濉溪县", + "regionId": 340621 + } + ], + "name": "淮北市", + "regionId": 340600 + }, + { + "counties": [ + { + "name": "铜官区", + "regionId": 340705 + }, + { + "name": "义安区", + "regionId": 340706 + }, + { + "name": "郊区", + "regionId": 340711 + }, + { + "name": "枞阳县", + "regionId": 340722 + } + ], + "name": "铜陵市", + "regionId": 340700 + }, + { + "counties": [ + { + "name": "迎江区", + "regionId": 340802 + }, + { + "name": "大观区", + "regionId": 340803 + }, + { + "name": "宜秀区", + "regionId": 340811 + }, + { + "name": "怀宁县", + "regionId": 340822 + }, + { + "name": "太湖县", + "regionId": 340825 + }, + { + "name": "宿松县", + "regionId": 340826 + }, + { + "name": "望江县", + "regionId": 340827 + }, + { + "name": "岳西县", + "regionId": 340828 + }, + { + "name": "桐城市", + "regionId": 340881 + }, + { + "name": "潜山市", + "regionId": 340882 + } + ], + "name": "安庆市", + "regionId": 340800 + }, + { + "counties": [ + { + "name": "屯溪区", + "regionId": 341002 + }, + { + "name": "黄山区", + "regionId": 341003 + }, + { + "name": "徽州区", + "regionId": 341004 + }, + { + "name": "歙县", + "regionId": 341021 + }, + { + "name": "休宁县", + "regionId": 341022 + }, + { + "name": "黟县", + "regionId": 341023 + }, + { + "name": "祁门县", + "regionId": 341024 + } + ], + "name": "黄山市", + "regionId": 341000 + }, + { + "counties": [ + { + "name": "琅琊区", + "regionId": 341102 + }, + { + "name": "南谯区", + "regionId": 341103 + }, + { + "name": "来安县", + "regionId": 341122 + }, + { + "name": "全椒县", + "regionId": 341124 + }, + { + "name": "定远县", + "regionId": 341125 + }, + { + "name": "凤阳县", + "regionId": 341126 + }, + { + "name": "天长市", + "regionId": 341181 + }, + { + "name": "明光市", + "regionId": 341182 + } + ], + "name": "滁州市", + "regionId": 341100 + }, + { + "counties": [ + { + "name": "颍州区", + "regionId": 341202 + }, + { + "name": "颍东区", + "regionId": 341203 + }, + { + "name": "颍泉区", + "regionId": 341204 + }, + { + "name": "临泉县", + "regionId": 341221 + }, + { + "name": "太和县", + "regionId": 341222 + }, + { + "name": "阜南县", + "regionId": 341225 + }, + { + "name": "颍上县", + "regionId": 341226 + }, + { + "name": "界首市", + "regionId": 341282 + } + ], + "name": "阜阳市", + "regionId": 341200 + }, + { + "counties": [ + { + "name": "埇桥区", + "regionId": 341302 + }, + { + "name": "砀山县", + "regionId": 341321 + }, + { + "name": "萧县", + "regionId": 341322 + }, + { + "name": "灵璧县", + "regionId": 341323 + }, + { + "name": "泗县", + "regionId": 341324 + } + ], + "name": "宿州市", + "regionId": 341300 + }, + { + "counties": [ + { + "name": "金安区", + "regionId": 341502 + }, + { + "name": "裕安区", + "regionId": 341503 + }, + { + "name": "叶集区", + "regionId": 341504 + }, + { + "name": "霍邱县", + "regionId": 341522 + }, + { + "name": "舒城县", + "regionId": 341523 + }, + { + "name": "金寨县", + "regionId": 341524 + }, + { + "name": "霍山县", + "regionId": 341525 + } + ], + "name": "六安市", + "regionId": 341500 + }, + { + "counties": [ + { + "name": "谯城区", + "regionId": 341602 + }, + { + "name": "涡阳县", + "regionId": 341621 + }, + { + "name": "蒙城县", + "regionId": 341622 + }, + { + "name": "利辛县", + "regionId": 341623 + } + ], + "name": "亳州市", + "regionId": 341600 + }, + { + "counties": [ + { + "name": "贵池区", + "regionId": 341702 + }, + { + "name": "东至县", + "regionId": 341721 + }, + { + "name": "石台县", + "regionId": 341722 + }, + { + "name": "青阳县", + "regionId": 341723 + } + ], + "name": "池州市", + "regionId": 341700 + }, + { + "counties": [ + { + "name": "宣州区", + "regionId": 341802 + }, + { + "name": "郎溪县", + "regionId": 341821 + }, + { + "name": "泾县", + "regionId": 341823 + }, + { + "name": "绩溪县", + "regionId": 341824 + }, + { + "name": "旌德县", + "regionId": 341825 + }, + { + "name": "宁国市", + "regionId": 341881 + }, + { + "name": "广德市", + "regionId": 341882 + } + ], + "name": "宣城市", + "regionId": 341800 + } + ], + "name": "安徽省", + "regionId": 340000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "东湖区", + "regionId": 360102 + }, + { + "name": "西湖区", + "regionId": 360103 + }, + { + "name": "青云谱区", + "regionId": 360104 + }, + { + "name": "青山湖区", + "regionId": 360111 + }, + { + "name": "新建区", + "regionId": 360112 + }, + { + "name": "红谷滩区", + "regionId": 360113 + }, + { + "name": "南昌县", + "regionId": 360121 + }, + { + "name": "安义县", + "regionId": 360123 + }, + { + "name": "进贤县", + "regionId": 360124 + } + ], + "name": "南昌市", + "regionId": 360100 + }, + { + "counties": [ + { + "name": "昌江区", + "regionId": 360202 + }, + { + "name": "珠山区", + "regionId": 360203 + }, + { + "name": "浮梁县", + "regionId": 360222 + }, + { + "name": "乐平市", + "regionId": 360281 + } + ], + "name": "景德镇市", + "regionId": 360200 + }, + { + "counties": [ + { + "name": "安源区", + "regionId": 360302 + }, + { + "name": "湘东区", + "regionId": 360313 + }, + { + "name": "莲花县", + "regionId": 360321 + }, + { + "name": "上栗县", + "regionId": 360322 + }, + { + "name": "芦溪县", + "regionId": 360323 + } + ], + "name": "萍乡市", + "regionId": 360300 + }, + { + "counties": [ + { + "name": "濂溪区", + "regionId": 360402 + }, + { + "name": "浔阳区", + "regionId": 360403 + }, + { + "name": "柴桑区", + "regionId": 360404 + }, + { + "name": "武宁县", + "regionId": 360423 + }, + { + "name": "修水县", + "regionId": 360424 + }, + { + "name": "永修县", + "regionId": 360425 + }, + { + "name": "德安县", + "regionId": 360426 + }, + { + "name": "都昌县", + "regionId": 360428 + }, + { + "name": "湖口县", + "regionId": 360429 + }, + { + "name": "彭泽县", + "regionId": 360430 + }, + { + "name": "瑞昌市", + "regionId": 360481 + }, + { + "name": "共青城市", + "regionId": 360482 + }, + { + "name": "庐山市", + "regionId": 360483 + } + ], + "name": "九江市", + "regionId": 360400 + }, + { + "counties": [ + { + "name": "渝水区", + "regionId": 360502 + }, + { + "name": "分宜县", + "regionId": 360521 + } + ], + "name": "新余市", + "regionId": 360500 + }, + { + "counties": [ + { + "name": "月湖区", + "regionId": 360602 + }, + { + "name": "余江区", + "regionId": 360603 + }, + { + "name": "贵溪市", + "regionId": 360681 + } + ], + "name": "鹰潭市", + "regionId": 360600 + }, + { + "counties": [ + { + "name": "章贡区", + "regionId": 360702 + }, + { + "name": "南康区", + "regionId": 360703 + }, + { + "name": "赣县区", + "regionId": 360704 + }, + { + "name": "信丰县", + "regionId": 360722 + }, + { + "name": "大余县", + "regionId": 360723 + }, + { + "name": "上犹县", + "regionId": 360724 + }, + { + "name": "崇义县", + "regionId": 360725 + }, + { + "name": "安远县", + "regionId": 360726 + }, + { + "name": "定南县", + "regionId": 360728 + }, + { + "name": "全南县", + "regionId": 360729 + }, + { + "name": "宁都县", + "regionId": 360730 + }, + { + "name": "于都县", + "regionId": 360731 + }, + { + "name": "兴国县", + "regionId": 360732 + }, + { + "name": "会昌县", + "regionId": 360733 + }, + { + "name": "寻乌县", + "regionId": 360734 + }, + { + "name": "石城县", + "regionId": 360735 + }, + { + "name": "瑞金市", + "regionId": 360781 + }, + { + "name": "龙南市", + "regionId": 360783 + } + ], + "name": "赣州市", + "regionId": 360700 + }, + { + "counties": [ + { + "name": "吉州区", + "regionId": 360802 + }, + { + "name": "青原区", + "regionId": 360803 + }, + { + "name": "吉安县", + "regionId": 360821 + }, + { + "name": "吉水县", + "regionId": 360822 + }, + { + "name": "峡江县", + "regionId": 360823 + }, + { + "name": "新干县", + "regionId": 360824 + }, + { + "name": "永丰县", + "regionId": 360825 + }, + { + "name": "泰和县", + "regionId": 360826 + }, + { + "name": "遂川县", + "regionId": 360827 + }, + { + "name": "万安县", + "regionId": 360828 + }, + { + "name": "安福县", + "regionId": 360829 + }, + { + "name": "永新县", + "regionId": 360830 + }, + { + "name": "井冈山市", + "regionId": 360881 + } + ], + "name": "吉安市", + "regionId": 360800 + }, + { + "counties": [ + { + "name": "袁州区", + "regionId": 360902 + }, + { + "name": "奉新县", + "regionId": 360921 + }, + { + "name": "万载县", + "regionId": 360922 + }, + { + "name": "上高县", + "regionId": 360923 + }, + { + "name": "宜丰县", + "regionId": 360924 + }, + { + "name": "靖安县", + "regionId": 360925 + }, + { + "name": "铜鼓县", + "regionId": 360926 + }, + { + "name": "丰城市", + "regionId": 360981 + }, + { + "name": "樟树市", + "regionId": 360982 + }, + { + "name": "高安市", + "regionId": 360983 + } + ], + "name": "宜春市", + "regionId": 360900 + }, + { + "counties": [ + { + "name": "临川区", + "regionId": 361002 + }, + { + "name": "东乡区", + "regionId": 361003 + }, + { + "name": "南城县", + "regionId": 361021 + }, + { + "name": "黎川县", + "regionId": 361022 + }, + { + "name": "南丰县", + "regionId": 361023 + }, + { + "name": "崇仁县", + "regionId": 361024 + }, + { + "name": "乐安县", + "regionId": 361025 + }, + { + "name": "宜黄县", + "regionId": 361026 + }, + { + "name": "金溪县", + "regionId": 361027 + }, + { + "name": "资溪县", + "regionId": 361028 + }, + { + "name": "广昌县", + "regionId": 361030 + } + ], + "name": "抚州市", + "regionId": 361000 + }, + { + "counties": [ + { + "name": "信州区", + "regionId": 361102 + }, + { + "name": "广丰区", + "regionId": 361103 + }, + { + "name": "广信区", + "regionId": 361104 + }, + { + "name": "玉山县", + "regionId": 361123 + }, + { + "name": "铅山县", + "regionId": 361124 + }, + { + "name": "横峰县", + "regionId": 361125 + }, + { + "name": "弋阳县", + "regionId": 361126 + }, + { + "name": "余干县", + "regionId": 361127 + }, + { + "name": "鄱阳县", + "regionId": 361128 + }, + { + "name": "万年县", + "regionId": 361129 + }, + { + "name": "婺源县", + "regionId": 361130 + }, + { + "name": "德兴市", + "regionId": 361181 + } + ], + "name": "上饶市", + "regionId": 361100 + } + ], + "name": "江西省", + "regionId": 360000 + } + ] + }, + { + "index": 2, + "part": "华中", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "中原区", + "regionId": 410102 + }, + { + "name": "二七区", + "regionId": 410103 + }, + { + "name": "管城回族区", + "regionId": 410104 + }, + { + "name": "金水区", + "regionId": 410105 + }, + { + "name": "上街区", + "regionId": 410106 + }, + { + "name": "惠济区", + "regionId": 410108 + }, + { + "name": "中牟县", + "regionId": 410122 + }, + { + "name": "巩义市", + "regionId": 410181 + }, + { + "name": "荥阳市", + "regionId": 410182 + }, + { + "name": "新密市", + "regionId": 410183 + }, + { + "name": "新郑市", + "regionId": 410184 + }, + { + "name": "登封市", + "regionId": 410185 + } + ], + "name": "郑州市", + "regionId": 410100 + }, + { + "counties": [ + { + "name": "龙亭区", + "regionId": 410202 + }, + { + "name": "顺河回族区", + "regionId": 410203 + }, + { + "name": "鼓楼区", + "regionId": 410204 + }, + { + "name": "禹王台区", + "regionId": 410205 + }, + { + "name": "祥符区", + "regionId": 410212 + }, + { + "name": "杞县", + "regionId": 410221 + }, + { + "name": "通许县", + "regionId": 410222 + }, + { + "name": "尉氏县", + "regionId": 410223 + }, + { + "name": "兰考县", + "regionId": 410225 + } + ], + "name": "开封市", + "regionId": 410200 + }, + { + "counties": [ + { + "name": "老城区", + "regionId": 410302 + }, + { + "name": "西工区", + "regionId": 410303 + }, + { + "name": "瀍河回族区", + "regionId": 410304 + }, + { + "name": "涧西区", + "regionId": 410305 + }, + { + "name": "偃师区", + "regionId": 410307 + }, + { + "name": "孟津区", + "regionId": 410308 + }, + { + "name": "洛龙区", + "regionId": 410311 + }, + { + "name": "新安县", + "regionId": 410323 + }, + { + "name": "栾川县", + "regionId": 410324 + }, + { + "name": "嵩县", + "regionId": 410325 + }, + { + "name": "汝阳县", + "regionId": 410326 + }, + { + "name": "宜阳县", + "regionId": 410327 + }, + { + "name": "洛宁县", + "regionId": 410328 + }, + { + "name": "伊川县", + "regionId": 410329 + } + ], + "name": "洛阳市", + "regionId": 410300 + }, + { + "counties": [ + { + "name": "新华区", + "regionId": 410402 + }, + { + "name": "卫东区", + "regionId": 410403 + }, + { + "name": "石龙区", + "regionId": 410404 + }, + { + "name": "湛河区", + "regionId": 410411 + }, + { + "name": "宝丰县", + "regionId": 410421 + }, + { + "name": "叶县", + "regionId": 410422 + }, + { + "name": "鲁山县", + "regionId": 410423 + }, + { + "name": "郏县", + "regionId": 410425 + }, + { + "name": "舞钢市", + "regionId": 410481 + }, + { + "name": "汝州市", + "regionId": 410482 + } + ], + "name": "平顶山市", + "regionId": 410400 + }, + { + "counties": [ + { + "name": "文峰区", + "regionId": 410502 + }, + { + "name": "北关区", + "regionId": 410503 + }, + { + "name": "殷都区", + "regionId": 410505 + }, + { + "name": "龙安区", + "regionId": 410506 + }, + { + "name": "安阳县", + "regionId": 410522 + }, + { + "name": "汤阴县", + "regionId": 410523 + }, + { + "name": "滑县", + "regionId": 410526 + }, + { + "name": "内黄县", + "regionId": 410527 + }, + { + "name": "林州市", + "regionId": 410581 + } + ], + "name": "安阳市", + "regionId": 410500 + }, + { + "counties": [ + { + "name": "鹤山区", + "regionId": 410602 + }, + { + "name": "山城区", + "regionId": 410603 + }, + { + "name": "淇滨区", + "regionId": 410611 + }, + { + "name": "浚县", + "regionId": 410621 + }, + { + "name": "淇县", + "regionId": 410622 + } + ], + "name": "鹤壁市", + "regionId": 410600 + }, + { + "counties": [ + { + "name": "红旗区", + "regionId": 410702 + }, + { + "name": "卫滨区", + "regionId": 410703 + }, + { + "name": "凤泉区", + "regionId": 410704 + }, + { + "name": "牧野区", + "regionId": 410711 + }, + { + "name": "新乡县", + "regionId": 410721 + }, + { + "name": "获嘉县", + "regionId": 410724 + }, + { + "name": "原阳县", + "regionId": 410725 + }, + { + "name": "延津县", + "regionId": 410726 + }, + { + "name": "封丘县", + "regionId": 410727 + }, + { + "name": "卫辉市", + "regionId": 410781 + }, + { + "name": "辉县市", + "regionId": 410782 + }, + { + "name": "长垣市", + "regionId": 410783 + } + ], + "name": "新乡市", + "regionId": 410700 + }, + { + "counties": [ + { + "name": "解放区", + "regionId": 410802 + }, + { + "name": "中站区", + "regionId": 410803 + }, + { + "name": "马村区", + "regionId": 410804 + }, + { + "name": "山阳区", + "regionId": 410811 + }, + { + "name": "修武县", + "regionId": 410821 + }, + { + "name": "博爱县", + "regionId": 410822 + }, + { + "name": "武陟县", + "regionId": 410823 + }, + { + "name": "温县", + "regionId": 410825 + }, + { + "name": "沁阳市", + "regionId": 410882 + }, + { + "name": "孟州市", + "regionId": 410883 + } + ], + "name": "焦作市", + "regionId": 410800 + }, + { + "counties": [ + { + "name": "华龙区", + "regionId": 410902 + }, + { + "name": "清丰县", + "regionId": 410922 + }, + { + "name": "南乐县", + "regionId": 410923 + }, + { + "name": "范县", + "regionId": 410926 + }, + { + "name": "台前县", + "regionId": 410927 + }, + { + "name": "濮阳县", + "regionId": 410928 + } + ], + "name": "濮阳市", + "regionId": 410900 + }, + { + "counties": [ + { + "name": "魏都区", + "regionId": 411002 + }, + { + "name": "建安区", + "regionId": 411003 + }, + { + "name": "鄢陵县", + "regionId": 411024 + }, + { + "name": "襄城县", + "regionId": 411025 + }, + { + "name": "禹州市", + "regionId": 411081 + }, + { + "name": "长葛市", + "regionId": 411082 + } + ], + "name": "许昌市", + "regionId": 411000 + }, + { + "counties": [ + { + "name": "源汇区", + "regionId": 411102 + }, + { + "name": "郾城区", + "regionId": 411103 + }, + { + "name": "召陵区", + "regionId": 411104 + }, + { + "name": "舞阳县", + "regionId": 411121 + }, + { + "name": "临颍县", + "regionId": 411122 + } + ], + "name": "漯河市", + "regionId": 411100 + }, + { + "counties": [ + { + "name": "湖滨区", + "regionId": 411202 + }, + { + "name": "陕州区", + "regionId": 411203 + }, + { + "name": "渑池县", + "regionId": 411221 + }, + { + "name": "卢氏县", + "regionId": 411224 + }, + { + "name": "义马市", + "regionId": 411281 + }, + { + "name": "灵宝市", + "regionId": 411282 + } + ], + "name": "三门峡市", + "regionId": 411200 + }, + { + "counties": [ + { + "name": "宛城区", + "regionId": 411302 + }, + { + "name": "卧龙区", + "regionId": 411303 + }, + { + "name": "南召县", + "regionId": 411321 + }, + { + "name": "方城县", + "regionId": 411322 + }, + { + "name": "西峡县", + "regionId": 411323 + }, + { + "name": "镇平县", + "regionId": 411324 + }, + { + "name": "内乡县", + "regionId": 411325 + }, + { + "name": "淅川县", + "regionId": 411326 + }, + { + "name": "社旗县", + "regionId": 411327 + }, + { + "name": "唐河县", + "regionId": 411328 + }, + { + "name": "新野县", + "regionId": 411329 + }, + { + "name": "桐柏县", + "regionId": 411330 + }, + { + "name": "邓州市", + "regionId": 411381 + } + ], + "name": "南阳市", + "regionId": 411300 + }, + { + "counties": [ + { + "name": "梁园区", + "regionId": 411402 + }, + { + "name": "睢阳区", + "regionId": 411403 + }, + { + "name": "民权县", + "regionId": 411421 + }, + { + "name": "睢县", + "regionId": 411422 + }, + { + "name": "宁陵县", + "regionId": 411423 + }, + { + "name": "柘城县", + "regionId": 411424 + }, + { + "name": "虞城县", + "regionId": 411425 + }, + { + "name": "夏邑县", + "regionId": 411426 + }, + { + "name": "永城市", + "regionId": 411481 + } + ], + "name": "商丘市", + "regionId": 411400 + }, + { + "counties": [ + { + "name": "浉河区", + "regionId": 411502 + }, + { + "name": "平桥区", + "regionId": 411503 + }, + { + "name": "罗山县", + "regionId": 411521 + }, + { + "name": "光山县", + "regionId": 411522 + }, + { + "name": "新县", + "regionId": 411523 + }, + { + "name": "商城县", + "regionId": 411524 + }, + { + "name": "固始县", + "regionId": 411525 + }, + { + "name": "潢川县", + "regionId": 411526 + }, + { + "name": "淮滨县", + "regionId": 411527 + }, + { + "name": "息县", + "regionId": 411528 + } + ], + "name": "信阳市", + "regionId": 411500 + }, + { + "counties": [ + { + "name": "川汇区", + "regionId": 411602 + }, + { + "name": "淮阳区", + "regionId": 411603 + }, + { + "name": "扶沟县", + "regionId": 411621 + }, + { + "name": "西华县", + "regionId": 411622 + }, + { + "name": "商水县", + "regionId": 411623 + }, + { + "name": "沈丘县", + "regionId": 411624 + }, + { + "name": "郸城县", + "regionId": 411625 + }, + { + "name": "太康县", + "regionId": 411627 + }, + { + "name": "鹿邑县", + "regionId": 411628 + }, + { + "name": "项城市", + "regionId": 411681 + } + ], + "name": "周口市", + "regionId": 411600 + }, + { + "counties": [ + { + "name": "驿城区", + "regionId": 411702 + }, + { + "name": "西平县", + "regionId": 411721 + }, + { + "name": "上蔡县", + "regionId": 411722 + }, + { + "name": "平舆县", + "regionId": 411723 + }, + { + "name": "正阳县", + "regionId": 411724 + }, + { + "name": "确山县", + "regionId": 411725 + }, + { + "name": "泌阳县", + "regionId": 411726 + }, + { + "name": "汝南县", + "regionId": 411727 + }, + { + "name": "遂平县", + "regionId": 411728 + }, + { + "name": "新蔡县", + "regionId": 411729 + } + ], + "name": "驻马店市", + "regionId": 411700 + }, + { + "counties": [ + { + "name": "济源市", + "regionId": 419001 + } + ], + "name": "省直辖县", + "regionId": 419000 + } + ], + "name": "河南省", + "regionId": 410000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "江岸区", + "regionId": 420102 + }, + { + "name": "江汉区", + "regionId": 420103 + }, + { + "name": "硚口区", + "regionId": 420104 + }, + { + "name": "汉阳区", + "regionId": 420105 + }, + { + "name": "武昌区", + "regionId": 420106 + }, + { + "name": "青山区", + "regionId": 420107 + }, + { + "name": "洪山区", + "regionId": 420111 + }, + { + "name": "东西湖区", + "regionId": 420112 + }, + { + "name": "汉南区", + "regionId": 420113 + }, + { + "name": "蔡甸区", + "regionId": 420114 + }, + { + "name": "江夏区", + "regionId": 420115 + }, + { + "name": "黄陂区", + "regionId": 420116 + }, + { + "name": "新洲区", + "regionId": 420117 + } + ], + "name": "武汉市", + "regionId": 420100 + }, + { + "counties": [ + { + "name": "黄石港区", + "regionId": 420202 + }, + { + "name": "西塞山区", + "regionId": 420203 + }, + { + "name": "下陆区", + "regionId": 420204 + }, + { + "name": "铁山区", + "regionId": 420205 + }, + { + "name": "阳新县", + "regionId": 420222 + }, + { + "name": "大冶市", + "regionId": 420281 + } + ], + "name": "黄石市", + "regionId": 420200 + }, + { + "counties": [ + { + "name": "茅箭区", + "regionId": 420302 + }, + { + "name": "张湾区", + "regionId": 420303 + }, + { + "name": "郧阳区", + "regionId": 420304 + }, + { + "name": "郧西县", + "regionId": 420322 + }, + { + "name": "竹山县", + "regionId": 420323 + }, + { + "name": "竹溪县", + "regionId": 420324 + }, + { + "name": "房县", + "regionId": 420325 + }, + { + "name": "丹江口市", + "regionId": 420381 + } + ], + "name": "十堰市", + "regionId": 420300 + }, + { + "counties": [ + { + "name": "西陵区", + "regionId": 420502 + }, + { + "name": "伍家岗区", + "regionId": 420503 + }, + { + "name": "点军区", + "regionId": 420504 + }, + { + "name": "猇亭区", + "regionId": 420505 + }, + { + "name": "夷陵区", + "regionId": 420506 + }, + { + "name": "远安县", + "regionId": 420525 + }, + { + "name": "兴山县", + "regionId": 420526 + }, + { + "name": "秭归县", + "regionId": 420527 + }, + { + "name": "长阳土家族自治县", + "regionId": 420528 + }, + { + "name": "五峰土家族自治县", + "regionId": 420529 + }, + { + "name": "宜都市", + "regionId": 420581 + }, + { + "name": "当阳市", + "regionId": 420582 + }, + { + "name": "枝江市", + "regionId": 420583 + } + ], + "name": "宜昌市", + "regionId": 420500 + }, + { + "counties": [ + { + "name": "襄城区", + "regionId": 420602 + }, + { + "name": "樊城区", + "regionId": 420606 + }, + { + "name": "襄州区", + "regionId": 420607 + }, + { + "name": "南漳县", + "regionId": 420624 + }, + { + "name": "谷城县", + "regionId": 420625 + }, + { + "name": "保康县", + "regionId": 420626 + }, + { + "name": "老河口市", + "regionId": 420682 + }, + { + "name": "枣阳市", + "regionId": 420683 + }, + { + "name": "宜城市", + "regionId": 420684 + } + ], + "name": "襄阳市", + "regionId": 420600 + }, + { + "counties": [ + { + "name": "梁子湖区", + "regionId": 420702 + }, + { + "name": "华容区", + "regionId": 420703 + }, + { + "name": "鄂城区", + "regionId": 420704 + } + ], + "name": "鄂州市", + "regionId": 420700 + }, + { + "counties": [ + { + "name": "东宝区", + "regionId": 420802 + }, + { + "name": "掇刀区", + "regionId": 420804 + }, + { + "name": "沙洋县", + "regionId": 420822 + }, + { + "name": "钟祥市", + "regionId": 420881 + }, + { + "name": "京山市", + "regionId": 420882 + } + ], + "name": "荆门市", + "regionId": 420800 + }, + { + "counties": [ + { + "name": "孝南区", + "regionId": 420902 + }, + { + "name": "孝昌县", + "regionId": 420921 + }, + { + "name": "大悟县", + "regionId": 420922 + }, + { + "name": "云梦县", + "regionId": 420923 + }, + { + "name": "应城市", + "regionId": 420981 + }, + { + "name": "安陆市", + "regionId": 420982 + }, + { + "name": "汉川市", + "regionId": 420984 + } + ], + "name": "孝感市", + "regionId": 420900 + }, + { + "counties": [ + { + "name": "沙市区", + "regionId": 421002 + }, + { + "name": "荆州区", + "regionId": 421003 + }, + { + "name": "公安县", + "regionId": 421022 + }, + { + "name": "江陵县", + "regionId": 421024 + }, + { + "name": "石首市", + "regionId": 421081 + }, + { + "name": "洪湖市", + "regionId": 421083 + }, + { + "name": "松滋市", + "regionId": 421087 + }, + { + "name": "监利市", + "regionId": 421088 + } + ], + "name": "荆州市", + "regionId": 421000 + }, + { + "counties": [ + { + "name": "黄州区", + "regionId": 421102 + }, + { + "name": "团风县", + "regionId": 421121 + }, + { + "name": "红安县", + "regionId": 421122 + }, + { + "name": "罗田县", + "regionId": 421123 + }, + { + "name": "英山县", + "regionId": 421124 + }, + { + "name": "浠水县", + "regionId": 421125 + }, + { + "name": "蕲春县", + "regionId": 421126 + }, + { + "name": "黄梅县", + "regionId": 421127 + }, + { + "name": "麻城市", + "regionId": 421181 + }, + { + "name": "武穴市", + "regionId": 421182 + } + ], + "name": "黄冈市", + "regionId": 421100 + }, + { + "counties": [ + { + "name": "咸安区", + "regionId": 421202 + }, + { + "name": "嘉鱼县", + "regionId": 421221 + }, + { + "name": "通城县", + "regionId": 421222 + }, + { + "name": "崇阳县", + "regionId": 421223 + }, + { + "name": "通山县", + "regionId": 421224 + }, + { + "name": "赤壁市", + "regionId": 421281 + } + ], + "name": "咸宁市", + "regionId": 421200 + }, + { + "counties": [ + { + "name": "曾都区", + "regionId": 421303 + }, + { + "name": "随县", + "regionId": 421321 + }, + { + "name": "广水市", + "regionId": 421381 + } + ], + "name": "随州市", + "regionId": 421300 + }, + { + "counties": [ + { + "name": "恩施市", + "regionId": 422801 + }, + { + "name": "利川市", + "regionId": 422802 + }, + { + "name": "建始县", + "regionId": 422822 + }, + { + "name": "巴东县", + "regionId": 422823 + }, + { + "name": "宣恩县", + "regionId": 422825 + }, + { + "name": "咸丰县", + "regionId": 422826 + }, + { + "name": "来凤县", + "regionId": 422827 + }, + { + "name": "鹤峰县", + "regionId": 422828 + } + ], + "name": "恩施土家族苗族自治州", + "regionId": 422800 + }, + { + "counties": [ + { + "name": "仙桃市", + "regionId": 429004 + }, + { + "name": "潜江市", + "regionId": 429005 + }, + { + "name": "天门市", + "regionId": 429006 + }, + { + "name": "神农架林区", + "regionId": 429021 + } + ], + "name": "省直辖县", + "regionId": 429000 + } + ], + "name": "湖北省", + "regionId": 420000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "芙蓉区", + "regionId": 430102 + }, + { + "name": "天心区", + "regionId": 430103 + }, + { + "name": "岳麓区", + "regionId": 430104 + }, + { + "name": "开福区", + "regionId": 430105 + }, + { + "name": "雨花区", + "regionId": 430111 + }, + { + "name": "望城区", + "regionId": 430112 + }, + { + "name": "长沙县", + "regionId": 430121 + }, + { + "name": "浏阳市", + "regionId": 430181 + }, + { + "name": "宁乡市", + "regionId": 430182 + } + ], + "name": "长沙市", + "regionId": 430100 + }, + { + "counties": [ + { + "name": "荷塘区", + "regionId": 430202 + }, + { + "name": "芦淞区", + "regionId": 430203 + }, + { + "name": "石峰区", + "regionId": 430204 + }, + { + "name": "天元区", + "regionId": 430211 + }, + { + "name": "渌口区", + "regionId": 430212 + }, + { + "name": "攸县", + "regionId": 430223 + }, + { + "name": "茶陵县", + "regionId": 430224 + }, + { + "name": "炎陵县", + "regionId": 430225 + }, + { + "name": "醴陵市", + "regionId": 430281 + } + ], + "name": "株洲市", + "regionId": 430200 + }, + { + "counties": [ + { + "name": "雨湖区", + "regionId": 430302 + }, + { + "name": "岳塘区", + "regionId": 430304 + }, + { + "name": "湘潭县", + "regionId": 430321 + }, + { + "name": "湘乡市", + "regionId": 430381 + }, + { + "name": "韶山市", + "regionId": 430382 + } + ], + "name": "湘潭市", + "regionId": 430300 + }, + { + "counties": [ + { + "name": "珠晖区", + "regionId": 430405 + }, + { + "name": "雁峰区", + "regionId": 430406 + }, + { + "name": "石鼓区", + "regionId": 430407 + }, + { + "name": "蒸湘区", + "regionId": 430408 + }, + { + "name": "南岳区", + "regionId": 430412 + }, + { + "name": "衡阳县", + "regionId": 430421 + }, + { + "name": "衡南县", + "regionId": 430422 + }, + { + "name": "衡山县", + "regionId": 430423 + }, + { + "name": "衡东县", + "regionId": 430424 + }, + { + "name": "祁东县", + "regionId": 430426 + }, + { + "name": "耒阳市", + "regionId": 430481 + }, + { + "name": "常宁市", + "regionId": 430482 + } + ], + "name": "衡阳市", + "regionId": 430400 + }, + { + "counties": [ + { + "name": "双清区", + "regionId": 430502 + }, + { + "name": "大祥区", + "regionId": 430503 + }, + { + "name": "北塔区", + "regionId": 430511 + }, + { + "name": "新邵县", + "regionId": 430522 + }, + { + "name": "邵阳县", + "regionId": 430523 + }, + { + "name": "隆回县", + "regionId": 430524 + }, + { + "name": "洞口县", + "regionId": 430525 + }, + { + "name": "绥宁县", + "regionId": 430527 + }, + { + "name": "新宁县", + "regionId": 430528 + }, + { + "name": "城步苗族自治县", + "regionId": 430529 + }, + { + "name": "武冈市", + "regionId": 430581 + }, + { + "name": "邵东市", + "regionId": 430582 + } + ], + "name": "邵阳市", + "regionId": 430500 + }, + { + "counties": [ + { + "name": "岳阳楼区", + "regionId": 430602 + }, + { + "name": "云溪区", + "regionId": 430603 + }, + { + "name": "君山区", + "regionId": 430611 + }, + { + "name": "岳阳县", + "regionId": 430621 + }, + { + "name": "华容县", + "regionId": 430623 + }, + { + "name": "湘阴县", + "regionId": 430624 + }, + { + "name": "平江县", + "regionId": 430626 + }, + { + "name": "汨罗市", + "regionId": 430681 + }, + { + "name": "临湘市", + "regionId": 430682 + } + ], + "name": "岳阳市", + "regionId": 430600 + }, + { + "counties": [ + { + "name": "武陵区", + "regionId": 430702 + }, + { + "name": "鼎城区", + "regionId": 430703 + }, + { + "name": "安乡县", + "regionId": 430721 + }, + { + "name": "汉寿县", + "regionId": 430722 + }, + { + "name": "澧县", + "regionId": 430723 + }, + { + "name": "临澧县", + "regionId": 430724 + }, + { + "name": "桃源县", + "regionId": 430725 + }, + { + "name": "石门县", + "regionId": 430726 + }, + { + "name": "津市市", + "regionId": 430781 + } + ], + "name": "常德市", + "regionId": 430700 + }, + { + "counties": [ + { + "name": "永定区", + "regionId": 430802 + }, + { + "name": "武陵源区", + "regionId": 430811 + }, + { + "name": "慈利县", + "regionId": 430821 + }, + { + "name": "桑植县", + "regionId": 430822 + } + ], + "name": "张家界市", + "regionId": 430800 + }, + { + "counties": [ + { + "name": "资阳区", + "regionId": 430902 + }, + { + "name": "赫山区", + "regionId": 430903 + }, + { + "name": "南县", + "regionId": 430921 + }, + { + "name": "桃江县", + "regionId": 430922 + }, + { + "name": "安化县", + "regionId": 430923 + }, + { + "name": "沅江市", + "regionId": 430981 + } + ], + "name": "益阳市", + "regionId": 430900 + }, + { + "counties": [ + { + "name": "北湖区", + "regionId": 431002 + }, + { + "name": "苏仙区", + "regionId": 431003 + }, + { + "name": "桂阳县", + "regionId": 431021 + }, + { + "name": "宜章县", + "regionId": 431022 + }, + { + "name": "永兴县", + "regionId": 431023 + }, + { + "name": "嘉禾县", + "regionId": 431024 + }, + { + "name": "临武县", + "regionId": 431025 + }, + { + "name": "汝城县", + "regionId": 431026 + }, + { + "name": "桂东县", + "regionId": 431027 + }, + { + "name": "安仁县", + "regionId": 431028 + }, + { + "name": "资兴市", + "regionId": 431081 + } + ], + "name": "郴州市", + "regionId": 431000 + }, + { + "counties": [ + { + "name": "零陵区", + "regionId": 431102 + }, + { + "name": "冷水滩区", + "regionId": 431103 + }, + { + "name": "东安县", + "regionId": 431122 + }, + { + "name": "双牌县", + "regionId": 431123 + }, + { + "name": "道县", + "regionId": 431124 + }, + { + "name": "江永县", + "regionId": 431125 + }, + { + "name": "宁远县", + "regionId": 431126 + }, + { + "name": "蓝山县", + "regionId": 431127 + }, + { + "name": "新田县", + "regionId": 431128 + }, + { + "name": "江华瑶族自治县", + "regionId": 431129 + }, + { + "name": "祁阳市", + "regionId": 431181 + } + ], + "name": "永州市", + "regionId": 431100 + }, + { + "counties": [ + { + "name": "鹤城区", + "regionId": 431202 + }, + { + "name": "中方县", + "regionId": 431221 + }, + { + "name": "沅陵县", + "regionId": 431222 + }, + { + "name": "辰溪县", + "regionId": 431223 + }, + { + "name": "溆浦县", + "regionId": 431224 + }, + { + "name": "会同县", + "regionId": 431225 + }, + { + "name": "麻阳苗族自治县", + "regionId": 431226 + }, + { + "name": "新晃侗族自治县", + "regionId": 431227 + }, + { + "name": "芷江侗族自治县", + "regionId": 431228 + }, + { + "name": "靖州苗族侗族自治县", + "regionId": 431229 + }, + { + "name": "通道侗族自治县", + "regionId": 431230 + }, + { + "name": "洪江市", + "regionId": 431281 + } + ], + "name": "怀化市", + "regionId": 431200 + }, + { + "counties": [ + { + "name": "娄星区", + "regionId": 431302 + }, + { + "name": "双峰县", + "regionId": 431321 + }, + { + "name": "新化县", + "regionId": 431322 + }, + { + "name": "冷水江市", + "regionId": 431381 + }, + { + "name": "涟源市", + "regionId": 431382 + } + ], + "name": "娄底市", + "regionId": 431300 + }, + { + "counties": [ + { + "name": "吉首市", + "regionId": 433101 + }, + { + "name": "泸溪县", + "regionId": 433122 + }, + { + "name": "凤凰县", + "regionId": 433123 + }, + { + "name": "花垣县", + "regionId": 433124 + }, + { + "name": "保靖县", + "regionId": 433125 + }, + { + "name": "古丈县", + "regionId": 433126 + }, + { + "name": "永顺县", + "regionId": 433127 + }, + { + "name": "龙山县", + "regionId": 433130 + } + ], + "name": "湘西土家族苗族自治州", + "regionId": 433100 + } + ], + "name": "湖南省", + "regionId": 430000 + } + ] + }, + { + "index": 3, + "part": "华南", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "鼓楼区", + "regionId": 350102 + }, + { + "name": "台江区", + "regionId": 350103 + }, + { + "name": "仓山区", + "regionId": 350104 + }, + { + "name": "马尾区", + "regionId": 350105 + }, + { + "name": "晋安区", + "regionId": 350111 + }, + { + "name": "长乐区", + "regionId": 350112 + }, + { + "name": "闽侯县", + "regionId": 350121 + }, + { + "name": "连江县", + "regionId": 350122 + }, + { + "name": "罗源县", + "regionId": 350123 + }, + { + "name": "闽清县", + "regionId": 350124 + }, + { + "name": "永泰县", + "regionId": 350125 + }, + { + "name": "平潭县", + "regionId": 350128 + }, + { + "name": "福清市", + "regionId": 350181 + } + ], + "name": "福州市", + "regionId": 350100 + }, + { + "counties": [ + { + "name": "思明区", + "regionId": 350203 + }, + { + "name": "海沧区", + "regionId": 350205 + }, + { + "name": "湖里区", + "regionId": 350206 + }, + { + "name": "集美区", + "regionId": 350211 + }, + { + "name": "同安区", + "regionId": 350212 + }, + { + "name": "翔安区", + "regionId": 350213 + } + ], + "name": "厦门市", + "regionId": 350200 + }, + { + "counties": [ + { + "name": "城厢区", + "regionId": 350302 + }, + { + "name": "涵江区", + "regionId": 350303 + }, + { + "name": "荔城区", + "regionId": 350304 + }, + { + "name": "秀屿区", + "regionId": 350305 + }, + { + "name": "仙游县", + "regionId": 350322 + } + ], + "name": "莆田市", + "regionId": 350300 + }, + { + "counties": [ + { + "name": "三元区", + "regionId": 350404 + }, + { + "name": "沙县区", + "regionId": 350405 + }, + { + "name": "明溪县", + "regionId": 350421 + }, + { + "name": "清流县", + "regionId": 350423 + }, + { + "name": "宁化县", + "regionId": 350424 + }, + { + "name": "大田县", + "regionId": 350425 + }, + { + "name": "尤溪县", + "regionId": 350426 + }, + { + "name": "将乐县", + "regionId": 350428 + }, + { + "name": "泰宁县", + "regionId": 350429 + }, + { + "name": "建宁县", + "regionId": 350430 + }, + { + "name": "永安市", + "regionId": 350481 + } + ], + "name": "三明市", + "regionId": 350400 + }, + { + "counties": [ + { + "name": "鲤城区", + "regionId": 350502 + }, + { + "name": "丰泽区", + "regionId": 350503 + }, + { + "name": "洛江区", + "regionId": 350504 + }, + { + "name": "泉港区", + "regionId": 350505 + }, + { + "name": "惠安县", + "regionId": 350521 + }, + { + "name": "安溪县", + "regionId": 350524 + }, + { + "name": "永春县", + "regionId": 350525 + }, + { + "name": "德化县", + "regionId": 350526 + }, + { + "name": "金门县", + "regionId": 350527 + }, + { + "name": "石狮市", + "regionId": 350581 + }, + { + "name": "晋江市", + "regionId": 350582 + }, + { + "name": "南安市", + "regionId": 350583 + } + ], + "name": "泉州市", + "regionId": 350500 + }, + { + "counties": [ + { + "name": "芗城区", + "regionId": 350602 + }, + { + "name": "龙文区", + "regionId": 350603 + }, + { + "name": "龙海区", + "regionId": 350604 + }, + { + "name": "长泰区", + "regionId": 350605 + }, + { + "name": "云霄县", + "regionId": 350622 + }, + { + "name": "漳浦县", + "regionId": 350623 + }, + { + "name": "诏安县", + "regionId": 350624 + }, + { + "name": "东山县", + "regionId": 350626 + }, + { + "name": "南靖县", + "regionId": 350627 + }, + { + "name": "平和县", + "regionId": 350628 + }, + { + "name": "华安县", + "regionId": 350629 + } + ], + "name": "漳州市", + "regionId": 350600 + }, + { + "counties": [ + { + "name": "延平区", + "regionId": 350702 + }, + { + "name": "建阳区", + "regionId": 350703 + }, + { + "name": "顺昌县", + "regionId": 350721 + }, + { + "name": "浦城县", + "regionId": 350722 + }, + { + "name": "光泽县", + "regionId": 350723 + }, + { + "name": "松溪县", + "regionId": 350724 + }, + { + "name": "政和县", + "regionId": 350725 + }, + { + "name": "邵武市", + "regionId": 350781 + }, + { + "name": "武夷山市", + "regionId": 350782 + }, + { + "name": "建瓯市", + "regionId": 350783 + } + ], + "name": "南平市", + "regionId": 350700 + }, + { + "counties": [ + { + "name": "新罗区", + "regionId": 350802 + }, + { + "name": "永定区", + "regionId": 350803 + }, + { + "name": "长汀县", + "regionId": 350821 + }, + { + "name": "上杭县", + "regionId": 350823 + }, + { + "name": "武平县", + "regionId": 350824 + }, + { + "name": "连城县", + "regionId": 350825 + }, + { + "name": "漳平市", + "regionId": 350881 + } + ], + "name": "龙岩市", + "regionId": 350800 + }, + { + "counties": [ + { + "name": "蕉城区", + "regionId": 350902 + }, + { + "name": "霞浦县", + "regionId": 350921 + }, + { + "name": "古田县", + "regionId": 350922 + }, + { + "name": "屏南县", + "regionId": 350923 + }, + { + "name": "寿宁县", + "regionId": 350924 + }, + { + "name": "周宁县", + "regionId": 350925 + }, + { + "name": "柘荣县", + "regionId": 350926 + }, + { + "name": "福安市", + "regionId": 350981 + }, + { + "name": "福鼎市", + "regionId": 350982 + } + ], + "name": "宁德市", + "regionId": 350900 + } + ], + "name": "福建省", + "regionId": 350000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "荔湾区", + "regionId": 440103 + }, + { + "name": "越秀区", + "regionId": 440104 + }, + { + "name": "海珠区", + "regionId": 440105 + }, + { + "name": "天河区", + "regionId": 440106 + }, + { + "name": "白云区", + "regionId": 440111 + }, + { + "name": "黄埔区", + "regionId": 440112 + }, + { + "name": "番禺区", + "regionId": 440113 + }, + { + "name": "花都区", + "regionId": 440114 + }, + { + "name": "南沙区", + "regionId": 440115 + }, + { + "name": "从化区", + "regionId": 440117 + }, + { + "name": "增城区", + "regionId": 440118 + } + ], + "name": "广州市", + "regionId": 440100 + }, + { + "counties": [ + { + "name": "武江区", + "regionId": 440203 + }, + { + "name": "浈江区", + "regionId": 440204 + }, + { + "name": "曲江区", + "regionId": 440205 + }, + { + "name": "始兴县", + "regionId": 440222 + }, + { + "name": "仁化县", + "regionId": 440224 + }, + { + "name": "翁源县", + "regionId": 440229 + }, + { + "name": "乳源瑶族自治县", + "regionId": 440232 + }, + { + "name": "新丰县", + "regionId": 440233 + }, + { + "name": "乐昌市", + "regionId": 440281 + }, + { + "name": "南雄市", + "regionId": 440282 + } + ], + "name": "韶关市", + "regionId": 440200 + }, + { + "counties": [ + { + "name": "罗湖区", + "regionId": 440303 + }, + { + "name": "福田区", + "regionId": 440304 + }, + { + "name": "南山区", + "regionId": 440305 + }, + { + "name": "宝安区", + "regionId": 440306 + }, + { + "name": "龙岗区", + "regionId": 440307 + }, + { + "name": "盐田区", + "regionId": 440308 + }, + { + "name": "龙华区", + "regionId": 440309 + }, + { + "name": "坪山区", + "regionId": 440310 + }, + { + "name": "光明区", + "regionId": 440311 + } + ], + "name": "深圳市", + "regionId": 440300 + }, + { + "counties": [ + { + "name": "香洲区", + "regionId": 440402 + }, + { + "name": "斗门区", + "regionId": 440403 + }, + { + "name": "金湾区", + "regionId": 440404 + } + ], + "name": "珠海市", + "regionId": 440400 + }, + { + "counties": [ + { + "name": "龙湖区", + "regionId": 440507 + }, + { + "name": "金平区", + "regionId": 440511 + }, + { + "name": "濠江区", + "regionId": 440512 + }, + { + "name": "潮阳区", + "regionId": 440513 + }, + { + "name": "潮南区", + "regionId": 440514 + }, + { + "name": "澄海区", + "regionId": 440515 + }, + { + "name": "南澳县", + "regionId": 440523 + } + ], + "name": "汕头市", + "regionId": 440500 + }, + { + "counties": [ + { + "name": "禅城区", + "regionId": 440604 + }, + { + "name": "南海区", + "regionId": 440605 + }, + { + "name": "顺德区", + "regionId": 440606 + }, + { + "name": "三水区", + "regionId": 440607 + }, + { + "name": "高明区", + "regionId": 440608 + } + ], + "name": "佛山市", + "regionId": 440600 + }, + { + "counties": [ + { + "name": "蓬江区", + "regionId": 440703 + }, + { + "name": "江海区", + "regionId": 440704 + }, + { + "name": "新会区", + "regionId": 440705 + }, + { + "name": "台山市", + "regionId": 440781 + }, + { + "name": "开平市", + "regionId": 440783 + }, + { + "name": "鹤山市", + "regionId": 440784 + }, + { + "name": "恩平市", + "regionId": 440785 + } + ], + "name": "江门市", + "regionId": 440700 + }, + { + "counties": [ + { + "name": "赤坎区", + "regionId": 440802 + }, + { + "name": "霞山区", + "regionId": 440803 + }, + { + "name": "坡头区", + "regionId": 440804 + }, + { + "name": "麻章区", + "regionId": 440811 + }, + { + "name": "遂溪县", + "regionId": 440823 + }, + { + "name": "徐闻县", + "regionId": 440825 + }, + { + "name": "廉江市", + "regionId": 440881 + }, + { + "name": "雷州市", + "regionId": 440882 + }, + { + "name": "吴川市", + "regionId": 440883 + } + ], + "name": "湛江市", + "regionId": 440800 + }, + { + "counties": [ + { + "name": "茂南区", + "regionId": 440902 + }, + { + "name": "电白区", + "regionId": 440904 + }, + { + "name": "高州市", + "regionId": 440981 + }, + { + "name": "化州市", + "regionId": 440982 + }, + { + "name": "信宜市", + "regionId": 440983 + } + ], + "name": "茂名市", + "regionId": 440900 + }, + { + "counties": [ + { + "name": "端州区", + "regionId": 441202 + }, + { + "name": "鼎湖区", + "regionId": 441203 + }, + { + "name": "高要区", + "regionId": 441204 + }, + { + "name": "广宁县", + "regionId": 441223 + }, + { + "name": "怀集县", + "regionId": 441224 + }, + { + "name": "封开县", + "regionId": 441225 + }, + { + "name": "德庆县", + "regionId": 441226 + }, + { + "name": "四会市", + "regionId": 441284 + } + ], + "name": "肇庆市", + "regionId": 441200 + }, + { + "counties": [ + { + "name": "惠城区", + "regionId": 441302 + }, + { + "name": "惠阳区", + "regionId": 441303 + }, + { + "name": "博罗县", + "regionId": 441322 + }, + { + "name": "惠东县", + "regionId": 441323 + }, + { + "name": "龙门县", + "regionId": 441324 + } + ], + "name": "惠州市", + "regionId": 441300 + }, + { + "counties": [ + { + "name": "梅江区", + "regionId": 441402 + }, + { + "name": "梅县区", + "regionId": 441403 + }, + { + "name": "大埔县", + "regionId": 441422 + }, + { + "name": "丰顺县", + "regionId": 441423 + }, + { + "name": "五华县", + "regionId": 441424 + }, + { + "name": "平远县", + "regionId": 441426 + }, + { + "name": "蕉岭县", + "regionId": 441427 + }, + { + "name": "兴宁市", + "regionId": 441481 + } + ], + "name": "梅州市", + "regionId": 441400 + }, + { + "counties": [ + { + "name": "城区", + "regionId": 441502 + }, + { + "name": "海丰县", + "regionId": 441521 + }, + { + "name": "陆河县", + "regionId": 441523 + }, + { + "name": "陆丰市", + "regionId": 441581 + } + ], + "name": "汕尾市", + "regionId": 441500 + }, + { + "counties": [ + { + "name": "源城区", + "regionId": 441602 + }, + { + "name": "紫金县", + "regionId": 441621 + }, + { + "name": "龙川县", + "regionId": 441622 + }, + { + "name": "连平县", + "regionId": 441623 + }, + { + "name": "和平县", + "regionId": 441624 + }, + { + "name": "东源县", + "regionId": 441625 + } + ], + "name": "河源市", + "regionId": 441600 + }, + { + "counties": [ + { + "name": "江城区", + "regionId": 441702 + }, + { + "name": "阳东区", + "regionId": 441704 + }, + { + "name": "阳西县", + "regionId": 441721 + }, + { + "name": "阳春市", + "regionId": 441781 + } + ], + "name": "阳江市", + "regionId": 441700 + }, + { + "counties": [ + { + "name": "清城区", + "regionId": 441802 + }, + { + "name": "清新区", + "regionId": 441803 + }, + { + "name": "佛冈县", + "regionId": 441821 + }, + { + "name": "阳山县", + "regionId": 441823 + }, + { + "name": "连山壮族瑶族自治县", + "regionId": 441825 + }, + { + "name": "连南瑶族自治县", + "regionId": 441826 + }, + { + "name": "英德市", + "regionId": 441881 + }, + { + "name": "连州市", + "regionId": 441882 + } + ], + "name": "清远市", + "regionId": 441800 + }, + { + "counties": [ + { + "name": "中堂镇", + "regionId": 441901 + }, + { + "name": "南城街道", + "regionId": 441903 + }, + { + "name": "长安镇", + "regionId": 441904 + }, + { + "name": "东坑镇", + "regionId": 441905 + }, + { + "name": "樟木头镇", + "regionId": 441906 + }, + { + "name": "莞城街道", + "regionId": 441907 + }, + { + "name": "石龙镇", + "regionId": 441908 + }, + { + "name": "桥头镇", + "regionId": 441909 + }, + { + "name": "万江街道", + "regionId": 441910 + }, + { + "name": "麻涌镇", + "regionId": 441911 + }, + { + "name": "虎门镇", + "regionId": 441912 + }, + { + "name": "谢岗镇", + "regionId": 441913 + }, + { + "name": "石碣镇", + "regionId": 441914 + }, + { + "name": "茶山镇", + "regionId": 441915 + }, + { + "name": "东城街道", + "regionId": 441916 + }, + { + "name": "洪梅镇", + "regionId": 441917 + }, + { + "name": "道滘镇", + "regionId": 441918 + }, + { + "name": "高埗镇", + "regionId": 441919 + }, + { + "name": "企石镇", + "regionId": 441920 + }, + { + "name": "凤岗镇", + "regionId": 441921 + }, + { + "name": "大岭山镇", + "regionId": 441922 + }, + { + "name": "松山湖", + "regionId": 441923 + }, + { + "name": "清溪镇", + "regionId": 441924 + }, + { + "name": "望牛墩镇", + "regionId": 441925 + }, + { + "name": "厚街镇", + "regionId": 441926 + }, + { + "name": "常平镇", + "regionId": 441927 + }, + { + "name": "寮步镇", + "regionId": 441928 + }, + { + "name": "石排镇", + "regionId": 441929 + }, + { + "name": "横沥镇", + "regionId": 441930 + }, + { + "name": "塘厦镇", + "regionId": 441931 + }, + { + "name": "黄江镇", + "regionId": 441932 + }, + { + "name": "大朗镇", + "regionId": 441933 + }, + { + "name": "东莞港", + "regionId": 441934 + }, + { + "name": "东莞生态园", + "regionId": 441935 + }, + { + "name": "沙田镇", + "regionId": 441990 + } + ], + "name": "东莞市", + "regionId": 441900 + }, + { + "counties": [ + { + "name": "南头镇", + "regionId": 442001 + }, + { + "name": "神湾镇", + "regionId": 442002 + }, + { + "name": "东凤镇", + "regionId": 442003 + }, + { + "name": "五桂山街道", + "regionId": 442004 + }, + { + "name": "黄圃镇", + "regionId": 442005 + }, + { + "name": "小榄镇", + "regionId": 442006 + }, + { + "name": "石岐街道", + "regionId": 442007 + }, + { + "name": "横栏镇", + "regionId": 442008 + }, + { + "name": "三角镇", + "regionId": 442009 + }, + { + "name": "三乡镇", + "regionId": 442010 + }, + { + "name": "港口镇", + "regionId": 442011 + }, + { + "name": "沙溪镇", + "regionId": 442012 + }, + { + "name": "板芙镇", + "regionId": 442013 + }, + { + "name": "东升镇", + "regionId": 442015 + }, + { + "name": "阜沙镇", + "regionId": 442016 + }, + { + "name": "民众镇", + "regionId": 442017 + }, + { + "name": "东区街道", + "regionId": 442018 + }, + { + "name": "火炬开发区街道", + "regionId": 442019 + }, + { + "name": "西区街道", + "regionId": 442020 + }, + { + "name": "南区街道", + "regionId": 442021 + }, + { + "name": "古镇镇", + "regionId": 442022 + }, + { + "name": "坦洲镇", + "regionId": 442023 + }, + { + "name": "大涌镇", + "regionId": 442024 + }, + { + "name": "南朗镇", + "regionId": 442025 + } + ], + "name": "中山市", + "regionId": 442000 + }, + { + "counties": [ + { + "name": "湘桥区", + "regionId": 445102 + }, + { + "name": "潮安区", + "regionId": 445103 + }, + { + "name": "饶平县", + "regionId": 445122 + } + ], + "name": "潮州市", + "regionId": 445100 + }, + { + "counties": [ + { + "name": "榕城区", + "regionId": 445202 + }, + { + "name": "揭东区", + "regionId": 445203 + }, + { + "name": "揭西县", + "regionId": 445222 + }, + { + "name": "惠来县", + "regionId": 445224 + }, + { + "name": "普宁市", + "regionId": 445281 + } + ], + "name": "揭阳市", + "regionId": 445200 + }, + { + "counties": [ + { + "name": "云城区", + "regionId": 445302 + }, + { + "name": "云安区", + "regionId": 445303 + }, + { + "name": "新兴县", + "regionId": 445321 + }, + { + "name": "郁南县", + "regionId": 445322 + }, + { + "name": "罗定市", + "regionId": 445381 + } + ], + "name": "云浮市", + "regionId": 445300 + } + ], + "name": "广东省", + "regionId": 440000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "兴宁区", + "regionId": 450102 + }, + { + "name": "青秀区", + "regionId": 450103 + }, + { + "name": "江南区", + "regionId": 450105 + }, + { + "name": "西乡塘区", + "regionId": 450107 + }, + { + "name": "良庆区", + "regionId": 450108 + }, + { + "name": "邕宁区", + "regionId": 450109 + }, + { + "name": "武鸣区", + "regionId": 450110 + }, + { + "name": "隆安县", + "regionId": 450123 + }, + { + "name": "马山县", + "regionId": 450124 + }, + { + "name": "上林县", + "regionId": 450125 + }, + { + "name": "宾阳县", + "regionId": 450126 + }, + { + "name": "横州市", + "regionId": 450181 + } + ], + "name": "南宁市", + "regionId": 450100 + }, + { + "counties": [ + { + "name": "城中区", + "regionId": 450202 + }, + { + "name": "鱼峰区", + "regionId": 450203 + }, + { + "name": "柳南区", + "regionId": 450204 + }, + { + "name": "柳北区", + "regionId": 450205 + }, + { + "name": "柳江区", + "regionId": 450206 + }, + { + "name": "柳城县", + "regionId": 450222 + }, + { + "name": "鹿寨县", + "regionId": 450223 + }, + { + "name": "融安县", + "regionId": 450224 + }, + { + "name": "融水苗族自治县", + "regionId": 450225 + }, + { + "name": "三江侗族自治县", + "regionId": 450226 + } + ], + "name": "柳州市", + "regionId": 450200 + }, + { + "counties": [ + { + "name": "秀峰区", + "regionId": 450302 + }, + { + "name": "叠彩区", + "regionId": 450303 + }, + { + "name": "象山区", + "regionId": 450304 + }, + { + "name": "七星区", + "regionId": 450305 + }, + { + "name": "雁山区", + "regionId": 450311 + }, + { + "name": "临桂区", + "regionId": 450312 + }, + { + "name": "阳朔县", + "regionId": 450321 + }, + { + "name": "灵川县", + "regionId": 450323 + }, + { + "name": "全州县", + "regionId": 450324 + }, + { + "name": "兴安县", + "regionId": 450325 + }, + { + "name": "永福县", + "regionId": 450326 + }, + { + "name": "灌阳县", + "regionId": 450327 + }, + { + "name": "龙胜各族自治县", + "regionId": 450328 + }, + { + "name": "资源县", + "regionId": 450329 + }, + { + "name": "平乐县", + "regionId": 450330 + }, + { + "name": "恭城瑶族自治县", + "regionId": 450332 + }, + { + "name": "荔浦市", + "regionId": 450381 + } + ], + "name": "桂林市", + "regionId": 450300 + }, + { + "counties": [ + { + "name": "万秀区", + "regionId": 450403 + }, + { + "name": "长洲区", + "regionId": 450405 + }, + { + "name": "龙圩区", + "regionId": 450406 + }, + { + "name": "苍梧县", + "regionId": 450421 + }, + { + "name": "藤县", + "regionId": 450422 + }, + { + "name": "蒙山县", + "regionId": 450423 + }, + { + "name": "岑溪市", + "regionId": 450481 + } + ], + "name": "梧州市", + "regionId": 450400 + }, + { + "counties": [ + { + "name": "海城区", + "regionId": 450502 + }, + { + "name": "银海区", + "regionId": 450503 + }, + { + "name": "铁山港区", + "regionId": 450512 + }, + { + "name": "合浦县", + "regionId": 450521 + } + ], + "name": "北海市", + "regionId": 450500 + }, + { + "counties": [ + { + "name": "港口区", + "regionId": 450602 + }, + { + "name": "防城区", + "regionId": 450603 + }, + { + "name": "上思县", + "regionId": 450621 + }, + { + "name": "东兴市", + "regionId": 450681 + } + ], + "name": "防城港市", + "regionId": 450600 + }, + { + "counties": [ + { + "name": "钦南区", + "regionId": 450702 + }, + { + "name": "钦北区", + "regionId": 450703 + }, + { + "name": "灵山县", + "regionId": 450721 + }, + { + "name": "浦北县", + "regionId": 450722 + } + ], + "name": "钦州市", + "regionId": 450700 + }, + { + "counties": [ + { + "name": "港北区", + "regionId": 450802 + }, + { + "name": "港南区", + "regionId": 450803 + }, + { + "name": "覃塘区", + "regionId": 450804 + }, + { + "name": "平南县", + "regionId": 450821 + }, + { + "name": "桂平市", + "regionId": 450881 + } + ], + "name": "贵港市", + "regionId": 450800 + }, + { + "counties": [ + { + "name": "玉州区", + "regionId": 450902 + }, + { + "name": "福绵区", + "regionId": 450903 + }, + { + "name": "容县", + "regionId": 450921 + }, + { + "name": "陆川县", + "regionId": 450922 + }, + { + "name": "博白县", + "regionId": 450923 + }, + { + "name": "兴业县", + "regionId": 450924 + }, + { + "name": "北流市", + "regionId": 450981 + } + ], + "name": "玉林市", + "regionId": 450900 + }, + { + "counties": [ + { + "name": "右江区", + "regionId": 451002 + }, + { + "name": "田阳区", + "regionId": 451003 + }, + { + "name": "田东县", + "regionId": 451022 + }, + { + "name": "德保县", + "regionId": 451024 + }, + { + "name": "那坡县", + "regionId": 451026 + }, + { + "name": "凌云县", + "regionId": 451027 + }, + { + "name": "乐业县", + "regionId": 451028 + }, + { + "name": "田林县", + "regionId": 451029 + }, + { + "name": "西林县", + "regionId": 451030 + }, + { + "name": "隆林各族自治县", + "regionId": 451031 + }, + { + "name": "靖西市", + "regionId": 451081 + }, + { + "name": "平果市", + "regionId": 451082 + } + ], + "name": "百色市", + "regionId": 451000 + }, + { + "counties": [ + { + "name": "八步区", + "regionId": 451102 + }, + { + "name": "平桂区", + "regionId": 451103 + }, + { + "name": "昭平县", + "regionId": 451121 + }, + { + "name": "钟山县", + "regionId": 451122 + }, + { + "name": "富川瑶族自治县", + "regionId": 451123 + } + ], + "name": "贺州市", + "regionId": 451100 + }, + { + "counties": [ + { + "name": "金城江区", + "regionId": 451202 + }, + { + "name": "宜州区", + "regionId": 451203 + }, + { + "name": "南丹县", + "regionId": 451221 + }, + { + "name": "天峨县", + "regionId": 451222 + }, + { + "name": "凤山县", + "regionId": 451223 + }, + { + "name": "东兰县", + "regionId": 451224 + }, + { + "name": "罗城仫佬族自治县", + "regionId": 451225 + }, + { + "name": "环江毛南族自治县", + "regionId": 451226 + }, + { + "name": "巴马瑶族自治县", + "regionId": 451227 + }, + { + "name": "都安瑶族自治县", + "regionId": 451228 + }, + { + "name": "大化瑶族自治县", + "regionId": 451229 + } + ], + "name": "河池市", + "regionId": 451200 + }, + { + "counties": [ + { + "name": "兴宾区", + "regionId": 451302 + }, + { + "name": "忻城县", + "regionId": 451321 + }, + { + "name": "象州县", + "regionId": 451322 + }, + { + "name": "武宣县", + "regionId": 451323 + }, + { + "name": "金秀瑶族自治县", + "regionId": 451324 + }, + { + "name": "合山市", + "regionId": 451381 + } + ], + "name": "来宾市", + "regionId": 451300 + }, + { + "counties": [ + { + "name": "江州区", + "regionId": 451402 + }, + { + "name": "扶绥县", + "regionId": 451421 + }, + { + "name": "宁明县", + "regionId": 451422 + }, + { + "name": "龙州县", + "regionId": 451423 + }, + { + "name": "大新县", + "regionId": 451424 + }, + { + "name": "天等县", + "regionId": 451425 + }, + { + "name": "凭祥市", + "regionId": 451481 + } + ], + "name": "崇左市", + "regionId": 451400 + } + ], + "name": "广西壮族自治区", + "regionId": 450000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "秀英区", + "regionId": 460105 + }, + { + "name": "龙华区", + "regionId": 460106 + }, + { + "name": "琼山区", + "regionId": 460107 + }, + { + "name": "美兰区", + "regionId": 460108 + } + ], + "name": "海口市", + "regionId": 460100 + }, + { + "counties": [ + { + "name": "海棠区", + "regionId": 460202 + }, + { + "name": "吉阳区", + "regionId": 460203 + }, + { + "name": "天涯区", + "regionId": 460204 + }, + { + "name": "崖州区", + "regionId": 460205 + } + ], + "name": "三亚市", + "regionId": 460200 + }, + { + "counties": [ + { + "name": "西沙区", + "regionId": 460321 + }, + { + "name": "南沙区", + "regionId": 460322 + } + ], + "name": "三沙市", + "regionId": 460300 + }, + { + "counties": [ + { + "name": "那大镇", + "regionId": 460401 + }, + { + "name": "和庆镇", + "regionId": 460402 + }, + { + "name": "南丰镇", + "regionId": 460403 + }, + { + "name": "大成镇", + "regionId": 460404 + }, + { + "name": "雅星镇", + "regionId": 460405 + }, + { + "name": "兰洋镇", + "regionId": 460406 + }, + { + "name": "光村镇", + "regionId": 460407 + }, + { + "name": "木棠镇", + "regionId": 460408 + }, + { + "name": "海头镇", + "regionId": 460409 + }, + { + "name": "峨蔓镇", + "regionId": 460410 + }, + { + "name": "王五镇", + "regionId": 460411 + }, + { + "name": "白马井镇", + "regionId": 460412 + }, + { + "name": "中和镇", + "regionId": 460413 + }, + { + "name": "排浦镇", + "regionId": 460414 + }, + { + "name": "东成镇", + "regionId": 460415 + }, + { + "name": "新州镇", + "regionId": 460416 + }, + { + "name": "洋浦经济开发区", + "regionId": 460417 + }, + { + "name": "华南热作学院", + "regionId": 460418 + } + ], + "name": "儋州市", + "regionId": 460400 + }, + { + "counties": [ + { + "name": "五指山市", + "regionId": 469001 + }, + { + "name": "琼海市", + "regionId": 469002 + }, + { + "name": "文昌市", + "regionId": 469005 + }, + { + "name": "万宁市", + "regionId": 469006 + }, + { + "name": "东方市", + "regionId": 469007 + }, + { + "name": "定安县", + "regionId": 469021 + }, + { + "name": "屯昌县", + "regionId": 469022 + }, + { + "name": "澄迈县", + "regionId": 469023 + }, + { + "name": "临高县", + "regionId": 469024 + }, + { + "name": "白沙黎族自治县", + "regionId": 469025 + }, + { + "name": "昌江黎族自治县", + "regionId": 469026 + }, + { + "name": "乐东黎族自治县", + "regionId": 469027 + }, + { + "name": "陵水黎族自治县", + "regionId": 469028 + }, + { + "name": "保亭黎族苗族自治县", + "regionId": 469029 + }, + { + "name": "琼中黎族苗族自治县", + "regionId": 469030 + } + ], + "name": "省直辖县", + "regionId": 469000 + } + ], + "name": "海南省", + "regionId": 460000 + } + ] + }, + { + "index": 4, + "part": "华北", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "东城区", + "regionId": 110101 + }, + { + "name": "西城区", + "regionId": 110102 + }, + { + "name": "朝阳区", + "regionId": 110105 + }, + { + "name": "丰台区", + "regionId": 110106 + }, + { + "name": "石景山区", + "regionId": 110107 + }, + { + "name": "海淀区", + "regionId": 110108 + }, + { + "name": "门头沟区", + "regionId": 110109 + }, + { + "name": "房山区", + "regionId": 110111 + }, + { + "name": "通州区", + "regionId": 110112 + }, + { + "name": "顺义区", + "regionId": 110113 + }, + { + "name": "昌平区", + "regionId": 110114 + }, + { + "name": "大兴区", + "regionId": 110115 + }, + { + "name": "怀柔区", + "regionId": 110116 + }, + { + "name": "平谷区", + "regionId": 110117 + }, + { + "name": "密云区", + "regionId": 110118 + }, + { + "name": "延庆区", + "regionId": 110119 + } + ], + "name": "北京市", + "regionId": 110100 + } + ], + "name": "北京市", + "regionId": 110000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "和平区", + "regionId": 120101 + }, + { + "name": "河东区", + "regionId": 120102 + }, + { + "name": "河西区", + "regionId": 120103 + }, + { + "name": "南开区", + "regionId": 120104 + }, + { + "name": "河北区", + "regionId": 120105 + }, + { + "name": "红桥区", + "regionId": 120106 + }, + { + "name": "东丽区", + "regionId": 120110 + }, + { + "name": "西青区", + "regionId": 120111 + }, + { + "name": "津南区", + "regionId": 120112 + }, + { + "name": "北辰区", + "regionId": 120113 + }, + { + "name": "武清区", + "regionId": 120114 + }, + { + "name": "宝坻区", + "regionId": 120115 + }, + { + "name": "滨海新区", + "regionId": 120116 + }, + { + "name": "宁河区", + "regionId": 120117 + }, + { + "name": "静海区", + "regionId": 120118 + }, + { + "name": "蓟州区", + "regionId": 120119 + } + ], + "name": "天津市", + "regionId": 120100 + } + ], + "name": "天津市", + "regionId": 120000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "长安区", + "regionId": 130102 + }, + { + "name": "桥西区", + "regionId": 130104 + }, + { + "name": "新华区", + "regionId": 130105 + }, + { + "name": "井陉矿区", + "regionId": 130107 + }, + { + "name": "裕华区", + "regionId": 130108 + }, + { + "name": "藁城区", + "regionId": 130109 + }, + { + "name": "鹿泉区", + "regionId": 130110 + }, + { + "name": "栾城区", + "regionId": 130111 + }, + { + "name": "井陉县", + "regionId": 130121 + }, + { + "name": "正定县", + "regionId": 130123 + }, + { + "name": "行唐县", + "regionId": 130125 + }, + { + "name": "灵寿县", + "regionId": 130126 + }, + { + "name": "高邑县", + "regionId": 130127 + }, + { + "name": "深泽县", + "regionId": 130128 + }, + { + "name": "赞皇县", + "regionId": 130129 + }, + { + "name": "无极县", + "regionId": 130130 + }, + { + "name": "平山县", + "regionId": 130131 + }, + { + "name": "元氏县", + "regionId": 130132 + }, + { + "name": "赵县", + "regionId": 130133 + }, + { + "name": "辛集市", + "regionId": 130181 + }, + { + "name": "晋州市", + "regionId": 130183 + }, + { + "name": "新乐市", + "regionId": 130184 + } + ], + "name": "石家庄市", + "regionId": 130100 + }, + { + "counties": [ + { + "name": "路南区", + "regionId": 130202 + }, + { + "name": "路北区", + "regionId": 130203 + }, + { + "name": "古冶区", + "regionId": 130204 + }, + { + "name": "开平区", + "regionId": 130205 + }, + { + "name": "丰南区", + "regionId": 130207 + }, + { + "name": "丰润区", + "regionId": 130208 + }, + { + "name": "曹妃甸区", + "regionId": 130209 + }, + { + "name": "滦南县", + "regionId": 130224 + }, + { + "name": "乐亭县", + "regionId": 130225 + }, + { + "name": "迁西县", + "regionId": 130227 + }, + { + "name": "玉田县", + "regionId": 130229 + }, + { + "name": "遵化市", + "regionId": 130281 + }, + { + "name": "迁安市", + "regionId": 130283 + }, + { + "name": "滦州市", + "regionId": 130284 + } + ], + "name": "唐山市", + "regionId": 130200 + }, + { + "counties": [ + { + "name": "海港区", + "regionId": 130302 + }, + { + "name": "山海关区", + "regionId": 130303 + }, + { + "name": "北戴河区", + "regionId": 130304 + }, + { + "name": "抚宁区", + "regionId": 130306 + }, + { + "name": "青龙满族自治县", + "regionId": 130321 + }, + { + "name": "昌黎县", + "regionId": 130322 + }, + { + "name": "卢龙县", + "regionId": 130324 + } + ], + "name": "秦皇岛市", + "regionId": 130300 + }, + { + "counties": [ + { + "name": "邯山区", + "regionId": 130402 + }, + { + "name": "丛台区", + "regionId": 130403 + }, + { + "name": "复兴区", + "regionId": 130404 + }, + { + "name": "峰峰矿区", + "regionId": 130406 + }, + { + "name": "肥乡区", + "regionId": 130407 + }, + { + "name": "永年区", + "regionId": 130408 + }, + { + "name": "临漳县", + "regionId": 130423 + }, + { + "name": "成安县", + "regionId": 130424 + }, + { + "name": "大名县", + "regionId": 130425 + }, + { + "name": "涉县", + "regionId": 130426 + }, + { + "name": "磁县", + "regionId": 130427 + }, + { + "name": "邱县", + "regionId": 130430 + }, + { + "name": "鸡泽县", + "regionId": 130431 + }, + { + "name": "广平县", + "regionId": 130432 + }, + { + "name": "馆陶县", + "regionId": 130433 + }, + { + "name": "魏县", + "regionId": 130434 + }, + { + "name": "曲周县", + "regionId": 130435 + }, + { + "name": "武安市", + "regionId": 130481 + } + ], + "name": "邯郸市", + "regionId": 130400 + }, + { + "counties": [ + { + "name": "襄都区", + "regionId": 130502 + }, + { + "name": "信都区", + "regionId": 130503 + }, + { + "name": "任泽区", + "regionId": 130505 + }, + { + "name": "南和区", + "regionId": 130506 + }, + { + "name": "临城县", + "regionId": 130522 + }, + { + "name": "内丘县", + "regionId": 130523 + }, + { + "name": "柏乡县", + "regionId": 130524 + }, + { + "name": "隆尧县", + "regionId": 130525 + }, + { + "name": "宁晋县", + "regionId": 130528 + }, + { + "name": "巨鹿县", + "regionId": 130529 + }, + { + "name": "新河县", + "regionId": 130530 + }, + { + "name": "广宗县", + "regionId": 130531 + }, + { + "name": "平乡县", + "regionId": 130532 + }, + { + "name": "威县", + "regionId": 130533 + }, + { + "name": "清河县", + "regionId": 130534 + }, + { + "name": "临西县", + "regionId": 130535 + }, + { + "name": "南宫市", + "regionId": 130581 + }, + { + "name": "沙河市", + "regionId": 130582 + } + ], + "name": "邢台市", + "regionId": 130500 + }, + { + "counties": [ + { + "name": "竞秀区", + "regionId": 130602 + }, + { + "name": "莲池区", + "regionId": 130606 + }, + { + "name": "满城区", + "regionId": 130607 + }, + { + "name": "清苑区", + "regionId": 130608 + }, + { + "name": "徐水区", + "regionId": 130609 + }, + { + "name": "涞水县", + "regionId": 130623 + }, + { + "name": "阜平县", + "regionId": 130624 + }, + { + "name": "定兴县", + "regionId": 130626 + }, + { + "name": "唐县", + "regionId": 130627 + }, + { + "name": "高阳县", + "regionId": 130628 + }, + { + "name": "容城县", + "regionId": 130629 + }, + { + "name": "涞源县", + "regionId": 130630 + }, + { + "name": "望都县", + "regionId": 130631 + }, + { + "name": "安新县", + "regionId": 130632 + }, + { + "name": "易县", + "regionId": 130633 + }, + { + "name": "曲阳县", + "regionId": 130634 + }, + { + "name": "蠡县", + "regionId": 130635 + }, + { + "name": "顺平县", + "regionId": 130636 + }, + { + "name": "博野县", + "regionId": 130637 + }, + { + "name": "雄县", + "regionId": 130638 + }, + { + "name": "涿州市", + "regionId": 130681 + }, + { + "name": "定州市", + "regionId": 130682 + }, + { + "name": "安国市", + "regionId": 130683 + }, + { + "name": "高碑店市", + "regionId": 130684 + } + ], + "name": "保定市", + "regionId": 130600 + }, + { + "counties": [ + { + "name": "桥东区", + "regionId": 130702 + }, + { + "name": "桥西区", + "regionId": 130703 + }, + { + "name": "宣化区", + "regionId": 130705 + }, + { + "name": "下花园区", + "regionId": 130706 + }, + { + "name": "万全区", + "regionId": 130708 + }, + { + "name": "崇礼区", + "regionId": 130709 + }, + { + "name": "张北县", + "regionId": 130722 + }, + { + "name": "康保县", + "regionId": 130723 + }, + { + "name": "沽源县", + "regionId": 130724 + }, + { + "name": "尚义县", + "regionId": 130725 + }, + { + "name": "蔚县", + "regionId": 130726 + }, + { + "name": "阳原县", + "regionId": 130727 + }, + { + "name": "怀安县", + "regionId": 130728 + }, + { + "name": "怀来县", + "regionId": 130730 + }, + { + "name": "涿鹿县", + "regionId": 130731 + }, + { + "name": "赤城县", + "regionId": 130732 + } + ], + "name": "张家口市", + "regionId": 130700 + }, + { + "counties": [ + { + "name": "双桥区", + "regionId": 130802 + }, + { + "name": "双滦区", + "regionId": 130803 + }, + { + "name": "鹰手营子矿区", + "regionId": 130804 + }, + { + "name": "承德县", + "regionId": 130821 + }, + { + "name": "兴隆县", + "regionId": 130822 + }, + { + "name": "滦平县", + "regionId": 130824 + }, + { + "name": "隆化县", + "regionId": 130825 + }, + { + "name": "丰宁满族自治县", + "regionId": 130826 + }, + { + "name": "宽城满族自治县", + "regionId": 130827 + }, + { + "name": "围场满族蒙古族自治县", + "regionId": 130828 + }, + { + "name": "平泉市", + "regionId": 130881 + } + ], + "name": "承德市", + "regionId": 130800 + }, + { + "counties": [ + { + "name": "新华区", + "regionId": 130902 + }, + { + "name": "运河区", + "regionId": 130903 + }, + { + "name": "沧县", + "regionId": 130921 + }, + { + "name": "青县", + "regionId": 130922 + }, + { + "name": "东光县", + "regionId": 130923 + }, + { + "name": "海兴县", + "regionId": 130924 + }, + { + "name": "盐山县", + "regionId": 130925 + }, + { + "name": "肃宁县", + "regionId": 130926 + }, + { + "name": "南皮县", + "regionId": 130927 + }, + { + "name": "吴桥县", + "regionId": 130928 + }, + { + "name": "献县", + "regionId": 130929 + }, + { + "name": "孟村回族自治县", + "regionId": 130930 + }, + { + "name": "泊头市", + "regionId": 130981 + }, + { + "name": "任丘市", + "regionId": 130982 + }, + { + "name": "黄骅市", + "regionId": 130983 + }, + { + "name": "河间市", + "regionId": 130984 + } + ], + "name": "沧州市", + "regionId": 130900 + }, + { + "counties": [ + { + "name": "安次区", + "regionId": 131002 + }, + { + "name": "广阳区", + "regionId": 131003 + }, + { + "name": "固安县", + "regionId": 131022 + }, + { + "name": "永清县", + "regionId": 131023 + }, + { + "name": "香河县", + "regionId": 131024 + }, + { + "name": "大城县", + "regionId": 131025 + }, + { + "name": "文安县", + "regionId": 131026 + }, + { + "name": "大厂回族自治县", + "regionId": 131028 + }, + { + "name": "霸州市", + "regionId": 131081 + }, + { + "name": "三河市", + "regionId": 131082 + } + ], + "name": "廊坊市", + "regionId": 131000 + }, + { + "counties": [ + { + "name": "桃城区", + "regionId": 131102 + }, + { + "name": "冀州区", + "regionId": 131103 + }, + { + "name": "枣强县", + "regionId": 131121 + }, + { + "name": "武邑县", + "regionId": 131122 + }, + { + "name": "武强县", + "regionId": 131123 + }, + { + "name": "饶阳县", + "regionId": 131124 + }, + { + "name": "安平县", + "regionId": 131125 + }, + { + "name": "故城县", + "regionId": 131126 + }, + { + "name": "景县", + "regionId": 131127 + }, + { + "name": "阜城县", + "regionId": 131128 + }, + { + "name": "深州市", + "regionId": 131182 + } + ], + "name": "衡水市", + "regionId": 131100 + } + ], + "name": "河北省", + "regionId": 130000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "小店区", + "regionId": 140105 + }, + { + "name": "迎泽区", + "regionId": 140106 + }, + { + "name": "杏花岭区", + "regionId": 140107 + }, + { + "name": "尖草坪区", + "regionId": 140108 + }, + { + "name": "万柏林区", + "regionId": 140109 + }, + { + "name": "晋源区", + "regionId": 140110 + }, + { + "name": "清徐县", + "regionId": 140121 + }, + { + "name": "阳曲县", + "regionId": 140122 + }, + { + "name": "娄烦县", + "regionId": 140123 + }, + { + "name": "古交市", + "regionId": 140181 + } + ], + "name": "太原市", + "regionId": 140100 + }, + { + "counties": [ + { + "name": "新荣区", + "regionId": 140212 + }, + { + "name": "平城区", + "regionId": 140213 + }, + { + "name": "云冈区", + "regionId": 140214 + }, + { + "name": "云州区", + "regionId": 140215 + }, + { + "name": "阳高县", + "regionId": 140221 + }, + { + "name": "天镇县", + "regionId": 140222 + }, + { + "name": "广灵县", + "regionId": 140223 + }, + { + "name": "灵丘县", + "regionId": 140224 + }, + { + "name": "浑源县", + "regionId": 140225 + }, + { + "name": "左云县", + "regionId": 140226 + } + ], + "name": "大同市", + "regionId": 140200 + }, + { + "counties": [ + { + "name": "城区", + "regionId": 140302 + }, + { + "name": "矿区", + "regionId": 140303 + }, + { + "name": "郊区", + "regionId": 140311 + }, + { + "name": "平定县", + "regionId": 140321 + }, + { + "name": "盂县", + "regionId": 140322 + } + ], + "name": "阳泉市", + "regionId": 140300 + }, + { + "counties": [ + { + "name": "潞州区", + "regionId": 140403 + }, + { + "name": "上党区", + "regionId": 140404 + }, + { + "name": "屯留区", + "regionId": 140405 + }, + { + "name": "潞城区", + "regionId": 140406 + }, + { + "name": "襄垣县", + "regionId": 140423 + }, + { + "name": "平顺县", + "regionId": 140425 + }, + { + "name": "黎城县", + "regionId": 140426 + }, + { + "name": "壶关县", + "regionId": 140427 + }, + { + "name": "长子县", + "regionId": 140428 + }, + { + "name": "武乡县", + "regionId": 140429 + }, + { + "name": "沁县", + "regionId": 140430 + }, + { + "name": "沁源县", + "regionId": 140431 + } + ], + "name": "长治市", + "regionId": 140400 + }, + { + "counties": [ + { + "name": "城区", + "regionId": 140502 + }, + { + "name": "沁水县", + "regionId": 140521 + }, + { + "name": "阳城县", + "regionId": 140522 + }, + { + "name": "陵川县", + "regionId": 140524 + }, + { + "name": "泽州县", + "regionId": 140525 + }, + { + "name": "高平市", + "regionId": 140581 + } + ], + "name": "晋城市", + "regionId": 140500 + }, + { + "counties": [ + { + "name": "朔城区", + "regionId": 140602 + }, + { + "name": "平鲁区", + "regionId": 140603 + }, + { + "name": "山阴县", + "regionId": 140621 + }, + { + "name": "应县", + "regionId": 140622 + }, + { + "name": "右玉县", + "regionId": 140623 + }, + { + "name": "怀仁市", + "regionId": 140681 + } + ], + "name": "朔州市", + "regionId": 140600 + }, + { + "counties": [ + { + "name": "榆次区", + "regionId": 140702 + }, + { + "name": "太谷区", + "regionId": 140703 + }, + { + "name": "榆社县", + "regionId": 140721 + }, + { + "name": "左权县", + "regionId": 140722 + }, + { + "name": "和顺县", + "regionId": 140723 + }, + { + "name": "昔阳县", + "regionId": 140724 + }, + { + "name": "寿阳县", + "regionId": 140725 + }, + { + "name": "祁县", + "regionId": 140727 + }, + { + "name": "平遥县", + "regionId": 140728 + }, + { + "name": "灵石县", + "regionId": 140729 + }, + { + "name": "介休市", + "regionId": 140781 + } + ], + "name": "晋中市", + "regionId": 140700 + }, + { + "counties": [ + { + "name": "盐湖区", + "regionId": 140802 + }, + { + "name": "临猗县", + "regionId": 140821 + }, + { + "name": "万荣县", + "regionId": 140822 + }, + { + "name": "闻喜县", + "regionId": 140823 + }, + { + "name": "稷山县", + "regionId": 140824 + }, + { + "name": "新绛县", + "regionId": 140825 + }, + { + "name": "绛县", + "regionId": 140826 + }, + { + "name": "垣曲县", + "regionId": 140827 + }, + { + "name": "夏县", + "regionId": 140828 + }, + { + "name": "平陆县", + "regionId": 140829 + }, + { + "name": "芮城县", + "regionId": 140830 + }, + { + "name": "永济市", + "regionId": 140881 + }, + { + "name": "河津市", + "regionId": 140882 + } + ], + "name": "运城市", + "regionId": 140800 + }, + { + "counties": [ + { + "name": "忻府区", + "regionId": 140902 + }, + { + "name": "定襄县", + "regionId": 140921 + }, + { + "name": "五台县", + "regionId": 140922 + }, + { + "name": "代县", + "regionId": 140923 + }, + { + "name": "繁峙县", + "regionId": 140924 + }, + { + "name": "宁武县", + "regionId": 140925 + }, + { + "name": "静乐县", + "regionId": 140926 + }, + { + "name": "神池县", + "regionId": 140927 + }, + { + "name": "五寨县", + "regionId": 140928 + }, + { + "name": "岢岚县", + "regionId": 140929 + }, + { + "name": "河曲县", + "regionId": 140930 + }, + { + "name": "保德县", + "regionId": 140931 + }, + { + "name": "偏关县", + "regionId": 140932 + }, + { + "name": "原平市", + "regionId": 140981 + } + ], + "name": "忻州市", + "regionId": 140900 + }, + { + "counties": [ + { + "name": "尧都区", + "regionId": 141002 + }, + { + "name": "曲沃县", + "regionId": 141021 + }, + { + "name": "翼城县", + "regionId": 141022 + }, + { + "name": "襄汾县", + "regionId": 141023 + }, + { + "name": "洪洞县", + "regionId": 141024 + }, + { + "name": "古县", + "regionId": 141025 + }, + { + "name": "安泽县", + "regionId": 141026 + }, + { + "name": "浮山县", + "regionId": 141027 + }, + { + "name": "吉县", + "regionId": 141028 + }, + { + "name": "乡宁县", + "regionId": 141029 + }, + { + "name": "大宁县", + "regionId": 141030 + }, + { + "name": "隰县", + "regionId": 141031 + }, + { + "name": "永和县", + "regionId": 141032 + }, + { + "name": "蒲县", + "regionId": 141033 + }, + { + "name": "汾西县", + "regionId": 141034 + }, + { + "name": "侯马市", + "regionId": 141081 + }, + { + "name": "霍州市", + "regionId": 141082 + } + ], + "name": "临汾市", + "regionId": 141000 + }, + { + "counties": [ + { + "name": "离石区", + "regionId": 141102 + }, + { + "name": "文水县", + "regionId": 141121 + }, + { + "name": "交城县", + "regionId": 141122 + }, + { + "name": "兴县", + "regionId": 141123 + }, + { + "name": "临县", + "regionId": 141124 + }, + { + "name": "柳林县", + "regionId": 141125 + }, + { + "name": "石楼县", + "regionId": 141126 + }, + { + "name": "岚县", + "regionId": 141127 + }, + { + "name": "方山县", + "regionId": 141128 + }, + { + "name": "中阳县", + "regionId": 141129 + }, + { + "name": "交口县", + "regionId": 141130 + }, + { + "name": "孝义市", + "regionId": 141181 + }, + { + "name": "汾阳市", + "regionId": 141182 + } + ], + "name": "吕梁市", + "regionId": 141100 + } + ], + "name": "山西省", + "regionId": 140000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "新城区", + "regionId": 150102 + }, + { + "name": "回民区", + "regionId": 150103 + }, + { + "name": "玉泉区", + "regionId": 150104 + }, + { + "name": "赛罕区", + "regionId": 150105 + }, + { + "name": "土默特左旗", + "regionId": 150121 + }, + { + "name": "托克托县", + "regionId": 150122 + }, + { + "name": "和林格尔县", + "regionId": 150123 + }, + { + "name": "清水河县", + "regionId": 150124 + }, + { + "name": "武川县", + "regionId": 150125 + } + ], + "name": "呼和浩特市", + "regionId": 150100 + }, + { + "counties": [ + { + "name": "东河区", + "regionId": 150202 + }, + { + "name": "昆都仑区", + "regionId": 150203 + }, + { + "name": "青山区", + "regionId": 150204 + }, + { + "name": "石拐区", + "regionId": 150205 + }, + { + "name": "白云鄂博矿区", + "regionId": 150206 + }, + { + "name": "九原区", + "regionId": 150207 + }, + { + "name": "土默特右旗", + "regionId": 150221 + }, + { + "name": "固阳县", + "regionId": 150222 + }, + { + "name": "达尔罕茂明安联合旗", + "regionId": 150223 + } + ], + "name": "包头市", + "regionId": 150200 + }, + { + "counties": [ + { + "name": "海勃湾区", + "regionId": 150302 + }, + { + "name": "海南区", + "regionId": 150303 + }, + { + "name": "乌达区", + "regionId": 150304 + } + ], + "name": "乌海市", + "regionId": 150300 + }, + { + "counties": [ + { + "name": "红山区", + "regionId": 150402 + }, + { + "name": "元宝山区", + "regionId": 150403 + }, + { + "name": "松山区", + "regionId": 150404 + }, + { + "name": "阿鲁科尔沁旗", + "regionId": 150421 + }, + { + "name": "巴林左旗", + "regionId": 150422 + }, + { + "name": "巴林右旗", + "regionId": 150423 + }, + { + "name": "林西县", + "regionId": 150424 + }, + { + "name": "克什克腾旗", + "regionId": 150425 + }, + { + "name": "翁牛特旗", + "regionId": 150426 + }, + { + "name": "喀喇沁旗", + "regionId": 150428 + }, + { + "name": "宁城县", + "regionId": 150429 + }, + { + "name": "敖汉旗", + "regionId": 150430 + } + ], + "name": "赤峰市", + "regionId": 150400 + }, + { + "counties": [ + { + "name": "科尔沁区", + "regionId": 150502 + }, + { + "name": "科尔沁左翼中旗", + "regionId": 150521 + }, + { + "name": "科尔沁左翼后旗", + "regionId": 150522 + }, + { + "name": "开鲁县", + "regionId": 150523 + }, + { + "name": "库伦旗", + "regionId": 150524 + }, + { + "name": "奈曼旗", + "regionId": 150525 + }, + { + "name": "扎鲁特旗", + "regionId": 150526 + }, + { + "name": "霍林郭勒市", + "regionId": 150581 + } + ], + "name": "通辽市", + "regionId": 150500 + }, + { + "counties": [ + { + "name": "东胜区", + "regionId": 150602 + }, + { + "name": "康巴什区", + "regionId": 150603 + }, + { + "name": "达拉特旗", + "regionId": 150621 + }, + { + "name": "准格尔旗", + "regionId": 150622 + }, + { + "name": "鄂托克前旗", + "regionId": 150623 + }, + { + "name": "鄂托克旗", + "regionId": 150624 + }, + { + "name": "杭锦旗", + "regionId": 150625 + }, + { + "name": "乌审旗", + "regionId": 150626 + }, + { + "name": "伊金霍洛旗", + "regionId": 150627 + } + ], + "name": "鄂尔多斯市", + "regionId": 150600 + }, + { + "counties": [ + { + "name": "海拉尔区", + "regionId": 150702 + }, + { + "name": "扎赉诺尔区", + "regionId": 150703 + }, + { + "name": "阿荣旗", + "regionId": 150721 + }, + { + "name": "莫力达瓦达斡尔族自治旗", + "regionId": 150722 + }, + { + "name": "鄂伦春自治旗", + "regionId": 150723 + }, + { + "name": "鄂温克族自治旗", + "regionId": 150724 + }, + { + "name": "陈巴尔虎旗", + "regionId": 150725 + }, + { + "name": "新巴尔虎左旗", + "regionId": 150726 + }, + { + "name": "新巴尔虎右旗", + "regionId": 150727 + }, + { + "name": "满洲里市", + "regionId": 150781 + }, + { + "name": "牙克石市", + "regionId": 150782 + }, + { + "name": "扎兰屯市", + "regionId": 150783 + }, + { + "name": "额尔古纳市", + "regionId": 150784 + }, + { + "name": "根河市", + "regionId": 150785 + } + ], + "name": "呼伦贝尔市", + "regionId": 150700 + }, + { + "counties": [ + { + "name": "临河区", + "regionId": 150802 + }, + { + "name": "五原县", + "regionId": 150821 + }, + { + "name": "磴口县", + "regionId": 150822 + }, + { + "name": "乌拉特前旗", + "regionId": 150823 + }, + { + "name": "乌拉特中旗", + "regionId": 150824 + }, + { + "name": "乌拉特后旗", + "regionId": 150825 + }, + { + "name": "杭锦后旗", + "regionId": 150826 + } + ], + "name": "巴彦淖尔市", + "regionId": 150800 + }, + { + "counties": [ + { + "name": "集宁区", + "regionId": 150902 + }, + { + "name": "卓资县", + "regionId": 150921 + }, + { + "name": "化德县", + "regionId": 150922 + }, + { + "name": "商都县", + "regionId": 150923 + }, + { + "name": "兴和县", + "regionId": 150924 + }, + { + "name": "凉城县", + "regionId": 150925 + }, + { + "name": "察哈尔右翼前旗", + "regionId": 150926 + }, + { + "name": "察哈尔右翼中旗", + "regionId": 150927 + }, + { + "name": "察哈尔右翼后旗", + "regionId": 150928 + }, + { + "name": "四子王旗", + "regionId": 150929 + }, + { + "name": "丰镇市", + "regionId": 150981 + } + ], + "name": "乌兰察布市", + "regionId": 150900 + }, + { + "counties": [ + { + "name": "乌兰浩特市", + "regionId": 152201 + }, + { + "name": "阿尔山市", + "regionId": 152202 + }, + { + "name": "科尔沁右翼前旗", + "regionId": 152221 + }, + { + "name": "科尔沁右翼中旗", + "regionId": 152222 + }, + { + "name": "扎赉特旗", + "regionId": 152223 + }, + { + "name": "突泉县", + "regionId": 152224 + } + ], + "name": "兴安盟", + "regionId": 152200 + }, + { + "counties": [ + { + "name": "二连浩特市", + "regionId": 152501 + }, + { + "name": "锡林浩特市", + "regionId": 152502 + }, + { + "name": "阿巴嘎旗", + "regionId": 152522 + }, + { + "name": "苏尼特左旗", + "regionId": 152523 + }, + { + "name": "苏尼特右旗", + "regionId": 152524 + }, + { + "name": "东乌珠穆沁旗", + "regionId": 152525 + }, + { + "name": "西乌珠穆沁旗", + "regionId": 152526 + }, + { + "name": "太仆寺旗", + "regionId": 152527 + }, + { + "name": "镶黄旗", + "regionId": 152528 + }, + { + "name": "正镶白旗", + "regionId": 152529 + }, + { + "name": "正蓝旗", + "regionId": 152530 + }, + { + "name": "多伦县", + "regionId": 152531 + } + ], + "name": "锡林郭勒盟", + "regionId": 152500 + }, + { + "counties": [ + { + "name": "阿拉善左旗", + "regionId": 152921 + }, + { + "name": "阿拉善右旗", + "regionId": 152922 + }, + { + "name": "额济纳旗", + "regionId": 152923 + } + ], + "name": "阿拉善盟", + "regionId": 152900 + } + ], + "name": "内蒙古自治区", + "regionId": 150000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "历下区", + "regionId": 370102 + }, + { + "name": "市中区", + "regionId": 370103 + }, + { + "name": "槐荫区", + "regionId": 370104 + }, + { + "name": "天桥区", + "regionId": 370105 + }, + { + "name": "历城区", + "regionId": 370112 + }, + { + "name": "长清区", + "regionId": 370113 + }, + { + "name": "章丘区", + "regionId": 370114 + }, + { + "name": "济阳区", + "regionId": 370115 + }, + { + "name": "莱芜区", + "regionId": 370116 + }, + { + "name": "钢城区", + "regionId": 370117 + }, + { + "name": "平阴县", + "regionId": 370124 + }, + { + "name": "商河县", + "regionId": 370126 + } + ], + "name": "济南市", + "regionId": 370100 + }, + { + "counties": [ + { + "name": "市南区", + "regionId": 370202 + }, + { + "name": "市北区", + "regionId": 370203 + }, + { + "name": "黄岛区", + "regionId": 370211 + }, + { + "name": "崂山区", + "regionId": 370212 + }, + { + "name": "李沧区", + "regionId": 370213 + }, + { + "name": "城阳区", + "regionId": 370214 + }, + { + "name": "即墨区", + "regionId": 370215 + }, + { + "name": "胶州市", + "regionId": 370281 + }, + { + "name": "平度市", + "regionId": 370283 + }, + { + "name": "莱西市", + "regionId": 370285 + } + ], + "name": "青岛市", + "regionId": 370200 + }, + { + "counties": [ + { + "name": "淄川区", + "regionId": 370302 + }, + { + "name": "张店区", + "regionId": 370303 + }, + { + "name": "博山区", + "regionId": 370304 + }, + { + "name": "临淄区", + "regionId": 370305 + }, + { + "name": "周村区", + "regionId": 370306 + }, + { + "name": "桓台县", + "regionId": 370321 + }, + { + "name": "高青县", + "regionId": 370322 + }, + { + "name": "沂源县", + "regionId": 370323 + } + ], + "name": "淄博市", + "regionId": 370300 + }, + { + "counties": [ + { + "name": "市中区", + "regionId": 370402 + }, + { + "name": "薛城区", + "regionId": 370403 + }, + { + "name": "峄城区", + "regionId": 370404 + }, + { + "name": "台儿庄区", + "regionId": 370405 + }, + { + "name": "山亭区", + "regionId": 370406 + }, + { + "name": "滕州市", + "regionId": 370481 + } + ], + "name": "枣庄市", + "regionId": 370400 + }, + { + "counties": [ + { + "name": "东营区", + "regionId": 370502 + }, + { + "name": "河口区", + "regionId": 370503 + }, + { + "name": "垦利区", + "regionId": 370505 + }, + { + "name": "利津县", + "regionId": 370522 + }, + { + "name": "广饶县", + "regionId": 370523 + } + ], + "name": "东营市", + "regionId": 370500 + }, + { + "counties": [ + { + "name": "芝罘区", + "regionId": 370602 + }, + { + "name": "福山区", + "regionId": 370611 + }, + { + "name": "牟平区", + "regionId": 370612 + }, + { + "name": "莱山区", + "regionId": 370613 + }, + { + "name": "蓬莱区", + "regionId": 370614 + }, + { + "name": "龙口市", + "regionId": 370681 + }, + { + "name": "莱阳市", + "regionId": 370682 + }, + { + "name": "莱州市", + "regionId": 370683 + }, + { + "name": "招远市", + "regionId": 370685 + }, + { + "name": "栖霞市", + "regionId": 370686 + }, + { + "name": "海阳市", + "regionId": 370687 + } + ], + "name": "烟台市", + "regionId": 370600 + }, + { + "counties": [ + { + "name": "潍城区", + "regionId": 370702 + }, + { + "name": "寒亭区", + "regionId": 370703 + }, + { + "name": "坊子区", + "regionId": 370704 + }, + { + "name": "奎文区", + "regionId": 370705 + }, + { + "name": "临朐县", + "regionId": 370724 + }, + { + "name": "昌乐县", + "regionId": 370725 + }, + { + "name": "青州市", + "regionId": 370781 + }, + { + "name": "诸城市", + "regionId": 370782 + }, + { + "name": "寿光市", + "regionId": 370783 + }, + { + "name": "安丘市", + "regionId": 370784 + }, + { + "name": "高密市", + "regionId": 370785 + }, + { + "name": "昌邑市", + "regionId": 370786 + } + ], + "name": "潍坊市", + "regionId": 370700 + }, + { + "counties": [ + { + "name": "任城区", + "regionId": 370811 + }, + { + "name": "兖州区", + "regionId": 370812 + }, + { + "name": "微山县", + "regionId": 370826 + }, + { + "name": "鱼台县", + "regionId": 370827 + }, + { + "name": "金乡县", + "regionId": 370828 + }, + { + "name": "嘉祥县", + "regionId": 370829 + }, + { + "name": "汶上县", + "regionId": 370830 + }, + { + "name": "泗水县", + "regionId": 370831 + }, + { + "name": "梁山县", + "regionId": 370832 + }, + { + "name": "曲阜市", + "regionId": 370881 + }, + { + "name": "邹城市", + "regionId": 370883 + } + ], + "name": "济宁市", + "regionId": 370800 + }, + { + "counties": [ + { + "name": "泰山区", + "regionId": 370902 + }, + { + "name": "岱岳区", + "regionId": 370911 + }, + { + "name": "宁阳县", + "regionId": 370921 + }, + { + "name": "东平县", + "regionId": 370923 + }, + { + "name": "新泰市", + "regionId": 370982 + }, + { + "name": "肥城市", + "regionId": 370983 + } + ], + "name": "泰安市", + "regionId": 370900 + }, + { + "counties": [ + { + "name": "环翠区", + "regionId": 371002 + }, + { + "name": "文登区", + "regionId": 371003 + }, + { + "name": "荣成市", + "regionId": 371082 + }, + { + "name": "乳山市", + "regionId": 371083 + } + ], + "name": "威海市", + "regionId": 371000 + }, + { + "counties": [ + { + "name": "东港区", + "regionId": 371102 + }, + { + "name": "岚山区", + "regionId": 371103 + }, + { + "name": "五莲县", + "regionId": 371121 + }, + { + "name": "莒县", + "regionId": 371122 + } + ], + "name": "日照市", + "regionId": 371100 + }, + { + "counties": [ + { + "name": "兰山区", + "regionId": 371302 + }, + { + "name": "罗庄区", + "regionId": 371311 + }, + { + "name": "河东区", + "regionId": 371312 + }, + { + "name": "沂南县", + "regionId": 371321 + }, + { + "name": "郯城县", + "regionId": 371322 + }, + { + "name": "沂水县", + "regionId": 371323 + }, + { + "name": "兰陵县", + "regionId": 371324 + }, + { + "name": "费县", + "regionId": 371325 + }, + { + "name": "平邑县", + "regionId": 371326 + }, + { + "name": "莒南县", + "regionId": 371327 + }, + { + "name": "蒙阴县", + "regionId": 371328 + }, + { + "name": "临沭县", + "regionId": 371329 + } + ], + "name": "临沂市", + "regionId": 371300 + }, + { + "counties": [ + { + "name": "德城区", + "regionId": 371402 + }, + { + "name": "陵城区", + "regionId": 371403 + }, + { + "name": "宁津县", + "regionId": 371422 + }, + { + "name": "庆云县", + "regionId": 371423 + }, + { + "name": "临邑县", + "regionId": 371424 + }, + { + "name": "齐河县", + "regionId": 371425 + }, + { + "name": "平原县", + "regionId": 371426 + }, + { + "name": "夏津县", + "regionId": 371427 + }, + { + "name": "武城县", + "regionId": 371428 + }, + { + "name": "乐陵市", + "regionId": 371481 + }, + { + "name": "禹城市", + "regionId": 371482 + } + ], + "name": "德州市", + "regionId": 371400 + }, + { + "counties": [ + { + "name": "东昌府区", + "regionId": 371502 + }, + { + "name": "茌平区", + "regionId": 371503 + }, + { + "name": "阳谷县", + "regionId": 371521 + }, + { + "name": "莘县", + "regionId": 371522 + }, + { + "name": "东阿县", + "regionId": 371524 + }, + { + "name": "冠县", + "regionId": 371525 + }, + { + "name": "高唐县", + "regionId": 371526 + }, + { + "name": "临清市", + "regionId": 371581 + } + ], + "name": "聊城市", + "regionId": 371500 + }, + { + "counties": [ + { + "name": "滨城区", + "regionId": 371602 + }, + { + "name": "沾化区", + "regionId": 371603 + }, + { + "name": "惠民县", + "regionId": 371621 + }, + { + "name": "阳信县", + "regionId": 371622 + }, + { + "name": "无棣县", + "regionId": 371623 + }, + { + "name": "博兴县", + "regionId": 371625 + }, + { + "name": "邹平市", + "regionId": 371681 + } + ], + "name": "滨州市", + "regionId": 371600 + }, + { + "counties": [ + { + "name": "牡丹区", + "regionId": 371702 + }, + { + "name": "定陶区", + "regionId": 371703 + }, + { + "name": "曹县", + "regionId": 371721 + }, + { + "name": "单县", + "regionId": 371722 + }, + { + "name": "成武县", + "regionId": 371723 + }, + { + "name": "巨野县", + "regionId": 371724 + }, + { + "name": "郓城县", + "regionId": 371725 + }, + { + "name": "鄄城县", + "regionId": 371726 + }, + { + "name": "东明县", + "regionId": 371728 + } + ], + "name": "菏泽市", + "regionId": 371700 + } + ], + "name": "山东省", + "regionId": 370000 + } + ] + }, + { + "index": 5, + "part": "西北", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "新城区", + "regionId": 610102 + }, + { + "name": "碑林区", + "regionId": 610103 + }, + { + "name": "莲湖区", + "regionId": 610104 + }, + { + "name": "灞桥区", + "regionId": 610111 + }, + { + "name": "未央区", + "regionId": 610112 + }, + { + "name": "雁塔区", + "regionId": 610113 + }, + { + "name": "阎良区", + "regionId": 610114 + }, + { + "name": "临潼区", + "regionId": 610115 + }, + { + "name": "长安区", + "regionId": 610116 + }, + { + "name": "高陵区", + "regionId": 610117 + }, + { + "name": "鄠邑区", + "regionId": 610118 + }, + { + "name": "蓝田县", + "regionId": 610122 + }, + { + "name": "周至县", + "regionId": 610124 + } + ], + "name": "西安市", + "regionId": 610100 + }, + { + "counties": [ + { + "name": "王益区", + "regionId": 610202 + }, + { + "name": "印台区", + "regionId": 610203 + }, + { + "name": "耀州区", + "regionId": 610204 + }, + { + "name": "宜君县", + "regionId": 610222 + } + ], + "name": "铜川市", + "regionId": 610200 + }, + { + "counties": [ + { + "name": "渭滨区", + "regionId": 610302 + }, + { + "name": "金台区", + "regionId": 610303 + }, + { + "name": "陈仓区", + "regionId": 610304 + }, + { + "name": "凤翔区", + "regionId": 610305 + }, + { + "name": "岐山县", + "regionId": 610323 + }, + { + "name": "扶风县", + "regionId": 610324 + }, + { + "name": "眉县", + "regionId": 610326 + }, + { + "name": "陇县", + "regionId": 610327 + }, + { + "name": "千阳县", + "regionId": 610328 + }, + { + "name": "麟游县", + "regionId": 610329 + }, + { + "name": "凤县", + "regionId": 610330 + }, + { + "name": "太白县", + "regionId": 610331 + } + ], + "name": "宝鸡市", + "regionId": 610300 + }, + { + "counties": [ + { + "name": "秦都区", + "regionId": 610402 + }, + { + "name": "杨陵区", + "regionId": 610403 + }, + { + "name": "渭城区", + "regionId": 610404 + }, + { + "name": "三原县", + "regionId": 610422 + }, + { + "name": "泾阳县", + "regionId": 610423 + }, + { + "name": "乾县", + "regionId": 610424 + }, + { + "name": "礼泉县", + "regionId": 610425 + }, + { + "name": "永寿县", + "regionId": 610426 + }, + { + "name": "长武县", + "regionId": 610428 + }, + { + "name": "旬邑县", + "regionId": 610429 + }, + { + "name": "淳化县", + "regionId": 610430 + }, + { + "name": "武功县", + "regionId": 610431 + }, + { + "name": "兴平市", + "regionId": 610481 + }, + { + "name": "彬州市", + "regionId": 610482 + } + ], + "name": "咸阳市", + "regionId": 610400 + }, + { + "counties": [ + { + "name": "临渭区", + "regionId": 610502 + }, + { + "name": "华州区", + "regionId": 610503 + }, + { + "name": "潼关县", + "regionId": 610522 + }, + { + "name": "大荔县", + "regionId": 610523 + }, + { + "name": "合阳县", + "regionId": 610524 + }, + { + "name": "澄城县", + "regionId": 610525 + }, + { + "name": "蒲城县", + "regionId": 610526 + }, + { + "name": "白水县", + "regionId": 610527 + }, + { + "name": "富平县", + "regionId": 610528 + }, + { + "name": "韩城市", + "regionId": 610581 + }, + { + "name": "华阴市", + "regionId": 610582 + } + ], + "name": "渭南市", + "regionId": 610500 + }, + { + "counties": [ + { + "name": "宝塔区", + "regionId": 610602 + }, + { + "name": "安塞区", + "regionId": 610603 + }, + { + "name": "延长县", + "regionId": 610621 + }, + { + "name": "延川县", + "regionId": 610622 + }, + { + "name": "志丹县", + "regionId": 610625 + }, + { + "name": "吴起县", + "regionId": 610626 + }, + { + "name": "甘泉县", + "regionId": 610627 + }, + { + "name": "富县", + "regionId": 610628 + }, + { + "name": "洛川县", + "regionId": 610629 + }, + { + "name": "宜川县", + "regionId": 610630 + }, + { + "name": "黄龙县", + "regionId": 610631 + }, + { + "name": "黄陵县", + "regionId": 610632 + }, + { + "name": "子长市", + "regionId": 610681 + } + ], + "name": "延安市", + "regionId": 610600 + }, + { + "counties": [ + { + "name": "汉台区", + "regionId": 610702 + }, + { + "name": "南郑区", + "regionId": 610703 + }, + { + "name": "城固县", + "regionId": 610722 + }, + { + "name": "洋县", + "regionId": 610723 + }, + { + "name": "西乡县", + "regionId": 610724 + }, + { + "name": "勉县", + "regionId": 610725 + }, + { + "name": "宁强县", + "regionId": 610726 + }, + { + "name": "略阳县", + "regionId": 610727 + }, + { + "name": "镇巴县", + "regionId": 610728 + }, + { + "name": "留坝县", + "regionId": 610729 + }, + { + "name": "佛坪县", + "regionId": 610730 + } + ], + "name": "汉中市", + "regionId": 610700 + }, + { + "counties": [ + { + "name": "榆阳区", + "regionId": 610802 + }, + { + "name": "横山区", + "regionId": 610803 + }, + { + "name": "府谷县", + "regionId": 610822 + }, + { + "name": "靖边县", + "regionId": 610824 + }, + { + "name": "定边县", + "regionId": 610825 + }, + { + "name": "绥德县", + "regionId": 610826 + }, + { + "name": "米脂县", + "regionId": 610827 + }, + { + "name": "佳县", + "regionId": 610828 + }, + { + "name": "吴堡县", + "regionId": 610829 + }, + { + "name": "清涧县", + "regionId": 610830 + }, + { + "name": "子洲县", + "regionId": 610831 + }, + { + "name": "神木市", + "regionId": 610881 + } + ], + "name": "榆林市", + "regionId": 610800 + }, + { + "counties": [ + { + "name": "汉滨区", + "regionId": 610902 + }, + { + "name": "汉阴县", + "regionId": 610921 + }, + { + "name": "石泉县", + "regionId": 610922 + }, + { + "name": "宁陕县", + "regionId": 610923 + }, + { + "name": "紫阳县", + "regionId": 610924 + }, + { + "name": "岚皋县", + "regionId": 610925 + }, + { + "name": "平利县", + "regionId": 610926 + }, + { + "name": "镇坪县", + "regionId": 610927 + }, + { + "name": "白河县", + "regionId": 610929 + }, + { + "name": "旬阳市", + "regionId": 610981 + } + ], + "name": "安康市", + "regionId": 610900 + }, + { + "counties": [ + { + "name": "商州区", + "regionId": 611002 + }, + { + "name": "洛南县", + "regionId": 611021 + }, + { + "name": "丹凤县", + "regionId": 611022 + }, + { + "name": "商南县", + "regionId": 611023 + }, + { + "name": "山阳县", + "regionId": 611024 + }, + { + "name": "镇安县", + "regionId": 611025 + }, + { + "name": "柞水县", + "regionId": 611026 + } + ], + "name": "商洛市", + "regionId": 611000 + } + ], + "name": "陕西省", + "regionId": 610000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "城关区", + "regionId": 620102 + }, + { + "name": "七里河区", + "regionId": 620103 + }, + { + "name": "西固区", + "regionId": 620104 + }, + { + "name": "安宁区", + "regionId": 620105 + }, + { + "name": "红古区", + "regionId": 620111 + }, + { + "name": "永登县", + "regionId": 620121 + }, + { + "name": "皋兰县", + "regionId": 620122 + }, + { + "name": "榆中县", + "regionId": 620123 + } + ], + "name": "兰州市", + "regionId": 620100 + }, + { + "counties": [ + { + "name": "市辖区", + "regionId": 620201 + }, + { + "name": "雄关区", + "regionId": 620290 + }, + { + "name": "长城区", + "regionId": 620291 + }, + { + "name": "镜铁区", + "regionId": 620292 + }, + { + "name": "新城镇", + "regionId": 620293 + }, + { + "name": "峪泉镇", + "regionId": 620294 + }, + { + "name": "文殊镇", + "regionId": 620295 + } + ], + "name": "嘉峪关市", + "regionId": 620200 + }, + { + "counties": [ + { + "name": "金川区", + "regionId": 620302 + }, + { + "name": "永昌县", + "regionId": 620321 + } + ], + "name": "金昌市", + "regionId": 620300 + }, + { + "counties": [ + { + "name": "白银区", + "regionId": 620402 + }, + { + "name": "平川区", + "regionId": 620403 + }, + { + "name": "靖远县", + "regionId": 620421 + }, + { + "name": "会宁县", + "regionId": 620422 + }, + { + "name": "景泰县", + "regionId": 620423 + } + ], + "name": "白银市", + "regionId": 620400 + }, + { + "counties": [ + { + "name": "秦州区", + "regionId": 620502 + }, + { + "name": "麦积区", + "regionId": 620503 + }, + { + "name": "清水县", + "regionId": 620521 + }, + { + "name": "秦安县", + "regionId": 620522 + }, + { + "name": "甘谷县", + "regionId": 620523 + }, + { + "name": "武山县", + "regionId": 620524 + }, + { + "name": "张家川回族自治县", + "regionId": 620525 + } + ], + "name": "天水市", + "regionId": 620500 + }, + { + "counties": [ + { + "name": "凉州区", + "regionId": 620602 + }, + { + "name": "民勤县", + "regionId": 620621 + }, + { + "name": "古浪县", + "regionId": 620622 + }, + { + "name": "天祝藏族自治县", + "regionId": 620623 + } + ], + "name": "武威市", + "regionId": 620600 + }, + { + "counties": [ + { + "name": "甘州区", + "regionId": 620702 + }, + { + "name": "肃南裕固族自治县", + "regionId": 620721 + }, + { + "name": "民乐县", + "regionId": 620722 + }, + { + "name": "临泽县", + "regionId": 620723 + }, + { + "name": "高台县", + "regionId": 620724 + }, + { + "name": "山丹县", + "regionId": 620725 + } + ], + "name": "张掖市", + "regionId": 620700 + }, + { + "counties": [ + { + "name": "崆峒区", + "regionId": 620802 + }, + { + "name": "泾川县", + "regionId": 620821 + }, + { + "name": "灵台县", + "regionId": 620822 + }, + { + "name": "崇信县", + "regionId": 620823 + }, + { + "name": "庄浪县", + "regionId": 620825 + }, + { + "name": "静宁县", + "regionId": 620826 + }, + { + "name": "华亭市", + "regionId": 620881 + } + ], + "name": "平凉市", + "regionId": 620800 + }, + { + "counties": [ + { + "name": "肃州区", + "regionId": 620902 + }, + { + "name": "金塔县", + "regionId": 620921 + }, + { + "name": "瓜州县", + "regionId": 620922 + }, + { + "name": "肃北蒙古族自治县", + "regionId": 620923 + }, + { + "name": "阿克塞哈萨克族自治县", + "regionId": 620924 + }, + { + "name": "玉门市", + "regionId": 620981 + }, + { + "name": "敦煌市", + "regionId": 620982 + } + ], + "name": "酒泉市", + "regionId": 620900 + }, + { + "counties": [ + { + "name": "西峰区", + "regionId": 621002 + }, + { + "name": "庆城县", + "regionId": 621021 + }, + { + "name": "环县", + "regionId": 621022 + }, + { + "name": "华池县", + "regionId": 621023 + }, + { + "name": "合水县", + "regionId": 621024 + }, + { + "name": "正宁县", + "regionId": 621025 + }, + { + "name": "宁县", + "regionId": 621026 + }, + { + "name": "镇原县", + "regionId": 621027 + } + ], + "name": "庆阳市", + "regionId": 621000 + }, + { + "counties": [ + { + "name": "安定区", + "regionId": 621102 + }, + { + "name": "通渭县", + "regionId": 621121 + }, + { + "name": "陇西县", + "regionId": 621122 + }, + { + "name": "渭源县", + "regionId": 621123 + }, + { + "name": "临洮县", + "regionId": 621124 + }, + { + "name": "漳县", + "regionId": 621125 + }, + { + "name": "岷县", + "regionId": 621126 + } + ], + "name": "定西市", + "regionId": 621100 + }, + { + "counties": [ + { + "name": "武都区", + "regionId": 621202 + }, + { + "name": "成县", + "regionId": 621221 + }, + { + "name": "文县", + "regionId": 621222 + }, + { + "name": "宕昌县", + "regionId": 621223 + }, + { + "name": "康县", + "regionId": 621224 + }, + { + "name": "西和县", + "regionId": 621225 + }, + { + "name": "礼县", + "regionId": 621226 + }, + { + "name": "徽县", + "regionId": 621227 + }, + { + "name": "两当县", + "regionId": 621228 + } + ], + "name": "陇南市", + "regionId": 621200 + }, + { + "counties": [ + { + "name": "临夏市", + "regionId": 622901 + }, + { + "name": "临夏县", + "regionId": 622921 + }, + { + "name": "康乐县", + "regionId": 622922 + }, + { + "name": "永靖县", + "regionId": 622923 + }, + { + "name": "广河县", + "regionId": 622924 + }, + { + "name": "和政县", + "regionId": 622925 + }, + { + "name": "东乡族自治县", + "regionId": 622926 + }, + { + "name": "积石山保安族东乡族撒拉族自治县", + "regionId": 622927 + } + ], + "name": "临夏回族自治州", + "regionId": 622900 + }, + { + "counties": [ + { + "name": "合作市", + "regionId": 623001 + }, + { + "name": "临潭县", + "regionId": 623021 + }, + { + "name": "卓尼县", + "regionId": 623022 + }, + { + "name": "舟曲县", + "regionId": 623023 + }, + { + "name": "迭部县", + "regionId": 623024 + }, + { + "name": "玛曲县", + "regionId": 623025 + }, + { + "name": "碌曲县", + "regionId": 623026 + }, + { + "name": "夏河县", + "regionId": 623027 + } + ], + "name": "甘南藏族自治州", + "regionId": 623000 + } + ], + "name": "甘肃省", + "regionId": 620000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "城东区", + "regionId": 630102 + }, + { + "name": "城中区", + "regionId": 630103 + }, + { + "name": "城西区", + "regionId": 630104 + }, + { + "name": "城北区", + "regionId": 630105 + }, + { + "name": "湟中区", + "regionId": 630106 + }, + { + "name": "大通回族土族自治县", + "regionId": 630121 + }, + { + "name": "湟源县", + "regionId": 630123 + } + ], + "name": "西宁市", + "regionId": 630100 + }, + { + "counties": [ + { + "name": "乐都区", + "regionId": 630202 + }, + { + "name": "平安区", + "regionId": 630203 + }, + { + "name": "民和回族土族自治县", + "regionId": 630222 + }, + { + "name": "互助土族自治县", + "regionId": 630223 + }, + { + "name": "化隆回族自治县", + "regionId": 630224 + }, + { + "name": "循化撒拉族自治县", + "regionId": 630225 + } + ], + "name": "海东市", + "regionId": 630200 + }, + { + "counties": [ + { + "name": "门源回族自治县", + "regionId": 632221 + }, + { + "name": "祁连县", + "regionId": 632222 + }, + { + "name": "海晏县", + "regionId": 632223 + }, + { + "name": "刚察县", + "regionId": 632224 + } + ], + "name": "海北藏族自治州", + "regionId": 632200 + }, + { + "counties": [ + { + "name": "同仁市", + "regionId": 632301 + }, + { + "name": "尖扎县", + "regionId": 632322 + }, + { + "name": "泽库县", + "regionId": 632323 + }, + { + "name": "河南蒙古族自治县", + "regionId": 632324 + } + ], + "name": "黄南藏族自治州", + "regionId": 632300 + }, + { + "counties": [ + { + "name": "共和县", + "regionId": 632521 + }, + { + "name": "同德县", + "regionId": 632522 + }, + { + "name": "贵德县", + "regionId": 632523 + }, + { + "name": "兴海县", + "regionId": 632524 + }, + { + "name": "贵南县", + "regionId": 632525 + } + ], + "name": "海南藏族自治州", + "regionId": 632500 + }, + { + "counties": [ + { + "name": "玛沁县", + "regionId": 632621 + }, + { + "name": "班玛县", + "regionId": 632622 + }, + { + "name": "甘德县", + "regionId": 632623 + }, + { + "name": "达日县", + "regionId": 632624 + }, + { + "name": "久治县", + "regionId": 632625 + }, + { + "name": "玛多县", + "regionId": 632626 + } + ], + "name": "果洛藏族自治州", + "regionId": 632600 + }, + { + "counties": [ + { + "name": "玉树市", + "regionId": 632701 + }, + { + "name": "杂多县", + "regionId": 632722 + }, + { + "name": "称多县", + "regionId": 632723 + }, + { + "name": "治多县", + "regionId": 632724 + }, + { + "name": "囊谦县", + "regionId": 632725 + }, + { + "name": "曲麻莱县", + "regionId": 632726 + } + ], + "name": "玉树藏族自治州", + "regionId": 632700 + }, + { + "counties": [ + { + "name": "格尔木市", + "regionId": 632801 + }, + { + "name": "德令哈市", + "regionId": 632802 + }, + { + "name": "茫崖市", + "regionId": 632803 + }, + { + "name": "乌兰县", + "regionId": 632821 + }, + { + "name": "都兰县", + "regionId": 632822 + }, + { + "name": "天峻县", + "regionId": 632823 + }, + { + "name": "大柴旦行政委员会", + "regionId": 632857 + } + ], + "name": "海西蒙古族藏族自治州", + "regionId": 632800 + } + ], + "name": "青海省", + "regionId": 630000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "兴庆区", + "regionId": 640104 + }, + { + "name": "西夏区", + "regionId": 640105 + }, + { + "name": "金凤区", + "regionId": 640106 + }, + { + "name": "永宁县", + "regionId": 640121 + }, + { + "name": "贺兰县", + "regionId": 640122 + }, + { + "name": "灵武市", + "regionId": 640181 + } + ], + "name": "银川市", + "regionId": 640100 + }, + { + "counties": [ + { + "name": "大武口区", + "regionId": 640202 + }, + { + "name": "惠农区", + "regionId": 640205 + }, + { + "name": "平罗县", + "regionId": 640221 + } + ], + "name": "石嘴山市", + "regionId": 640200 + }, + { + "counties": [ + { + "name": "利通区", + "regionId": 640302 + }, + { + "name": "红寺堡区", + "regionId": 640303 + }, + { + "name": "盐池县", + "regionId": 640323 + }, + { + "name": "同心县", + "regionId": 640324 + }, + { + "name": "青铜峡市", + "regionId": 640381 + } + ], + "name": "吴忠市", + "regionId": 640300 + }, + { + "counties": [ + { + "name": "原州区", + "regionId": 640402 + }, + { + "name": "西吉县", + "regionId": 640422 + }, + { + "name": "隆德县", + "regionId": 640423 + }, + { + "name": "泾源县", + "regionId": 640424 + }, + { + "name": "彭阳县", + "regionId": 640425 + } + ], + "name": "固原市", + "regionId": 640400 + }, + { + "counties": [ + { + "name": "沙坡头区", + "regionId": 640502 + }, + { + "name": "中宁县", + "regionId": 640521 + }, + { + "name": "海原县", + "regionId": 640522 + } + ], + "name": "中卫市", + "regionId": 640500 + } + ], + "name": "宁夏回族自治区", + "regionId": 640000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "天山区", + "regionId": 650102 + }, + { + "name": "沙依巴克区", + "regionId": 650103 + }, + { + "name": "新市区", + "regionId": 650104 + }, + { + "name": "水磨沟区", + "regionId": 650105 + }, + { + "name": "头屯河区", + "regionId": 650106 + }, + { + "name": "达坂城区", + "regionId": 650107 + }, + { + "name": "米东区", + "regionId": 650109 + }, + { + "name": "乌鲁木齐县", + "regionId": 650121 + } + ], + "name": "乌鲁木齐市", + "regionId": 650100 + }, + { + "counties": [ + { + "name": "独山子区", + "regionId": 650202 + }, + { + "name": "克拉玛依区", + "regionId": 650203 + }, + { + "name": "白碱滩区", + "regionId": 650204 + }, + { + "name": "乌尔禾区", + "regionId": 650205 + } + ], + "name": "克拉玛依市", + "regionId": 650200 + }, + { + "counties": [ + { + "name": "高昌区", + "regionId": 650402 + }, + { + "name": "鄯善县", + "regionId": 650421 + }, + { + "name": "托克逊县", + "regionId": 650422 + } + ], + "name": "吐鲁番市", + "regionId": 650400 + }, + { + "counties": [ + { + "name": "伊州区", + "regionId": 650502 + }, + { + "name": "巴里坤哈萨克自治县", + "regionId": 650521 + }, + { + "name": "伊吾县", + "regionId": 650522 + } + ], + "name": "哈密市", + "regionId": 650500 + }, + { + "counties": [ + { + "name": "昌吉市", + "regionId": 652301 + }, + { + "name": "阜康市", + "regionId": 652302 + }, + { + "name": "呼图壁县", + "regionId": 652323 + }, + { + "name": "玛纳斯县", + "regionId": 652324 + }, + { + "name": "奇台县", + "regionId": 652325 + }, + { + "name": "吉木萨尔县", + "regionId": 652327 + }, + { + "name": "木垒哈萨克自治县", + "regionId": 652328 + } + ], + "name": "昌吉回族自治州", + "regionId": 652300 + }, + { + "counties": [ + { + "name": "博乐市", + "regionId": 652701 + }, + { + "name": "阿拉山口市", + "regionId": 652702 + }, + { + "name": "精河县", + "regionId": 652722 + }, + { + "name": "温泉县", + "regionId": 652723 + } + ], + "name": "博尔塔拉蒙古自治州", + "regionId": 652700 + }, + { + "counties": [ + { + "name": "库尔勒市", + "regionId": 652801 + }, + { + "name": "轮台县", + "regionId": 652822 + }, + { + "name": "尉犁县", + "regionId": 652823 + }, + { + "name": "若羌县", + "regionId": 652824 + }, + { + "name": "且末县", + "regionId": 652825 + }, + { + "name": "焉耆回族自治县", + "regionId": 652826 + }, + { + "name": "和静县", + "regionId": 652827 + }, + { + "name": "和硕县", + "regionId": 652828 + }, + { + "name": "博湖县", + "regionId": 652829 + } + ], + "name": "巴音郭楞蒙古自治州", + "regionId": 652800 + }, + { + "counties": [ + { + "name": "阿克苏市", + "regionId": 652901 + }, + { + "name": "库车市", + "regionId": 652902 + }, + { + "name": "温宿县", + "regionId": 652922 + }, + { + "name": "沙雅县", + "regionId": 652924 + }, + { + "name": "新和县", + "regionId": 652925 + }, + { + "name": "拜城县", + "regionId": 652926 + }, + { + "name": "乌什县", + "regionId": 652927 + }, + { + "name": "阿瓦提县", + "regionId": 652928 + }, + { + "name": "柯坪县", + "regionId": 652929 + } + ], + "name": "阿克苏地区", + "regionId": 652900 + }, + { + "counties": [ + { + "name": "阿图什市", + "regionId": 653001 + }, + { + "name": "阿克陶县", + "regionId": 653022 + }, + { + "name": "阿合奇县", + "regionId": 653023 + }, + { + "name": "乌恰县", + "regionId": 653024 + } + ], + "name": "克孜勒苏柯尔克孜自治州", + "regionId": 653000 + }, + { + "counties": [ + { + "name": "喀什市", + "regionId": 653101 + }, + { + "name": "疏附县", + "regionId": 653121 + }, + { + "name": "疏勒县", + "regionId": 653122 + }, + { + "name": "英吉沙县", + "regionId": 653123 + }, + { + "name": "泽普县", + "regionId": 653124 + }, + { + "name": "莎车县", + "regionId": 653125 + }, + { + "name": "叶城县", + "regionId": 653126 + }, + { + "name": "麦盖提县", + "regionId": 653127 + }, + { + "name": "岳普湖县", + "regionId": 653128 + }, + { + "name": "伽师县", + "regionId": 653129 + }, + { + "name": "巴楚县", + "regionId": 653130 + }, + { + "name": "塔什库尔干塔吉克自治县", + "regionId": 653131 + } + ], + "name": "喀什地区", + "regionId": 653100 + }, + { + "counties": [ + { + "name": "和田市", + "regionId": 653201 + }, + { + "name": "和田县", + "regionId": 653221 + }, + { + "name": "墨玉县", + "regionId": 653222 + }, + { + "name": "皮山县", + "regionId": 653223 + }, + { + "name": "洛浦县", + "regionId": 653224 + }, + { + "name": "策勒县", + "regionId": 653225 + }, + { + "name": "于田县", + "regionId": 653226 + }, + { + "name": "民丰县", + "regionId": 653227 + } + ], + "name": "和田地区", + "regionId": 653200 + }, + { + "counties": [ + { + "name": "伊宁市", + "regionId": 654002 + }, + { + "name": "奎屯市", + "regionId": 654003 + }, + { + "name": "霍尔果斯市", + "regionId": 654004 + }, + { + "name": "伊宁县", + "regionId": 654021 + }, + { + "name": "察布查尔锡伯自治县", + "regionId": 654022 + }, + { + "name": "霍城县", + "regionId": 654023 + }, + { + "name": "巩留县", + "regionId": 654024 + }, + { + "name": "新源县", + "regionId": 654025 + }, + { + "name": "昭苏县", + "regionId": 654026 + }, + { + "name": "特克斯县", + "regionId": 654027 + }, + { + "name": "尼勒克县", + "regionId": 654028 + } + ], + "name": "伊犁哈萨克自治州", + "regionId": 654000 + }, + { + "counties": [ + { + "name": "塔城市", + "regionId": 654201 + }, + { + "name": "乌苏市", + "regionId": 654202 + }, + { + "name": "沙湾市", + "regionId": 654203 + }, + { + "name": "额敏县", + "regionId": 654221 + }, + { + "name": "托里县", + "regionId": 654224 + }, + { + "name": "裕民县", + "regionId": 654225 + }, + { + "name": "和布克赛尔蒙古自治县", + "regionId": 654226 + } + ], + "name": "塔城地区", + "regionId": 654200 + }, + { + "counties": [ + { + "name": "阿勒泰市", + "regionId": 654301 + }, + { + "name": "布尔津县", + "regionId": 654321 + }, + { + "name": "富蕴县", + "regionId": 654322 + }, + { + "name": "福海县", + "regionId": 654323 + }, + { + "name": "哈巴河县", + "regionId": 654324 + }, + { + "name": "青河县", + "regionId": 654325 + }, + { + "name": "吉木乃县", + "regionId": 654326 + } + ], + "name": "阿勒泰地区", + "regionId": 654300 + }, + { + "counties": [ + { + "name": "石河子市", + "regionId": 659001 + }, + { + "name": "阿拉尔市", + "regionId": 659002 + }, + { + "name": "图木舒克市", + "regionId": 659003 + }, + { + "name": "五家渠市", + "regionId": 659004 + }, + { + "name": "北屯市", + "regionId": 659005 + }, + { + "name": "铁门关市", + "regionId": 659006 + }, + { + "name": "双河市", + "regionId": 659007 + }, + { + "name": "可克达拉市", + "regionId": 659008 + }, + { + "name": "昆玉市", + "regionId": 659009 + }, + { + "name": "胡杨河市", + "regionId": 659010 + }, + { + "name": "新星市", + "regionId": 659011 + }, + { + "name": "白杨市", + "regionId": 659012 + } + ], + "name": "自治区直辖县级行政区划", + "regionId": 659000 + } + ], + "name": "新疆维吾尔自治区", + "regionId": 650000 + } + ] + }, + { + "index": 6, + "part": "西南", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "万州区", + "regionId": 500101 + }, + { + "name": "涪陵区", + "regionId": 500102 + }, + { + "name": "渝中区", + "regionId": 500103 + }, + { + "name": "大渡口区", + "regionId": 500104 + }, + { + "name": "江北区", + "regionId": 500105 + }, + { + "name": "沙坪坝区", + "regionId": 500106 + }, + { + "name": "九龙坡区", + "regionId": 500107 + }, + { + "name": "南岸区", + "regionId": 500108 + }, + { + "name": "北碚区", + "regionId": 500109 + }, + { + "name": "綦江区", + "regionId": 500110 + }, + { + "name": "大足区", + "regionId": 500111 + }, + { + "name": "渝北区", + "regionId": 500112 + }, + { + "name": "巴南区", + "regionId": 500113 + }, + { + "name": "黔江区", + "regionId": 500114 + }, + { + "name": "长寿区", + "regionId": 500115 + }, + { + "name": "江津区", + "regionId": 500116 + }, + { + "name": "合川区", + "regionId": 500117 + }, + { + "name": "永川区", + "regionId": 500118 + }, + { + "name": "南川区", + "regionId": 500119 + }, + { + "name": "璧山区", + "regionId": 500120 + }, + { + "name": "铜梁区", + "regionId": 500151 + }, + { + "name": "潼南区", + "regionId": 500152 + }, + { + "name": "荣昌区", + "regionId": 500153 + }, + { + "name": "开州区", + "regionId": 500154 + }, + { + "name": "梁平区", + "regionId": 500155 + }, + { + "name": "武隆区", + "regionId": 500156 + }, + { + "name": "两江新区", + "regionId": 500157 + } + ], + "name": "重庆市", + "regionId": 500100 + }, + { + "counties": [ + { + "name": "城口县", + "regionId": 500229 + }, + { + "name": "丰都县", + "regionId": 500230 + }, + { + "name": "垫江县", + "regionId": 500231 + }, + { + "name": "忠县", + "regionId": 500233 + }, + { + "name": "云阳县", + "regionId": 500235 + }, + { + "name": "奉节县", + "regionId": 500236 + }, + { + "name": "巫山县", + "regionId": 500237 + }, + { + "name": "巫溪县", + "regionId": 500238 + }, + { + "name": "石柱土家族自治县", + "regionId": 500240 + }, + { + "name": "秀山土家族苗族自治县", + "regionId": 500241 + }, + { + "name": "酉阳土家族苗族自治县", + "regionId": 500242 + }, + { + "name": "彭水苗族土家族自治县", + "regionId": 500243 + } + ], + "name": "县", + "regionId": 500200 + } + ], + "name": "重庆市", + "regionId": 500000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "锦江区", + "regionId": 510104 + }, + { + "name": "青羊区", + "regionId": 510105 + }, + { + "name": "金牛区", + "regionId": 510106 + }, + { + "name": "武侯区", + "regionId": 510107 + }, + { + "name": "成华区", + "regionId": 510108 + }, + { + "name": "龙泉驿区", + "regionId": 510112 + }, + { + "name": "青白江区", + "regionId": 510113 + }, + { + "name": "新都区", + "regionId": 510114 + }, + { + "name": "温江区", + "regionId": 510115 + }, + { + "name": "双流区", + "regionId": 510116 + }, + { + "name": "郫都区", + "regionId": 510117 + }, + { + "name": "新津区", + "regionId": 510118 + }, + { + "name": "金堂县", + "regionId": 510121 + }, + { + "name": "大邑县", + "regionId": 510129 + }, + { + "name": "蒲江县", + "regionId": 510131 + }, + { + "name": "都江堰市", + "regionId": 510181 + }, + { + "name": "彭州市", + "regionId": 510182 + }, + { + "name": "邛崃市", + "regionId": 510183 + }, + { + "name": "崇州市", + "regionId": 510184 + }, + { + "name": "简阳市", + "regionId": 510185 + } + ], + "name": "成都市", + "regionId": 510100 + }, + { + "counties": [ + { + "name": "自流井区", + "regionId": 510302 + }, + { + "name": "贡井区", + "regionId": 510303 + }, + { + "name": "大安区", + "regionId": 510304 + }, + { + "name": "沿滩区", + "regionId": 510311 + }, + { + "name": "荣县", + "regionId": 510321 + }, + { + "name": "富顺县", + "regionId": 510322 + } + ], + "name": "自贡市", + "regionId": 510300 + }, + { + "counties": [ + { + "name": "东区", + "regionId": 510402 + }, + { + "name": "西区", + "regionId": 510403 + }, + { + "name": "仁和区", + "regionId": 510411 + }, + { + "name": "米易县", + "regionId": 510421 + }, + { + "name": "盐边县", + "regionId": 510422 + } + ], + "name": "攀枝花市", + "regionId": 510400 + }, + { + "counties": [ + { + "name": "江阳区", + "regionId": 510502 + }, + { + "name": "纳溪区", + "regionId": 510503 + }, + { + "name": "龙马潭区", + "regionId": 510504 + }, + { + "name": "泸县", + "regionId": 510521 + }, + { + "name": "合江县", + "regionId": 510522 + }, + { + "name": "叙永县", + "regionId": 510524 + }, + { + "name": "古蔺县", + "regionId": 510525 + } + ], + "name": "泸州市", + "regionId": 510500 + }, + { + "counties": [ + { + "name": "旌阳区", + "regionId": 510603 + }, + { + "name": "罗江区", + "regionId": 510604 + }, + { + "name": "中江县", + "regionId": 510623 + }, + { + "name": "广汉市", + "regionId": 510681 + }, + { + "name": "什邡市", + "regionId": 510682 + }, + { + "name": "绵竹市", + "regionId": 510683 + } + ], + "name": "德阳市", + "regionId": 510600 + }, + { + "counties": [ + { + "name": "涪城区", + "regionId": 510703 + }, + { + "name": "游仙区", + "regionId": 510704 + }, + { + "name": "安州区", + "regionId": 510705 + }, + { + "name": "三台县", + "regionId": 510722 + }, + { + "name": "盐亭县", + "regionId": 510723 + }, + { + "name": "梓潼县", + "regionId": 510725 + }, + { + "name": "北川羌族自治县", + "regionId": 510726 + }, + { + "name": "平武县", + "regionId": 510727 + }, + { + "name": "江油市", + "regionId": 510781 + } + ], + "name": "绵阳市", + "regionId": 510700 + }, + { + "counties": [ + { + "name": "利州区", + "regionId": 510802 + }, + { + "name": "昭化区", + "regionId": 510811 + }, + { + "name": "朝天区", + "regionId": 510812 + }, + { + "name": "旺苍县", + "regionId": 510821 + }, + { + "name": "青川县", + "regionId": 510822 + }, + { + "name": "剑阁县", + "regionId": 510823 + }, + { + "name": "苍溪县", + "regionId": 510824 + } + ], + "name": "广元市", + "regionId": 510800 + }, + { + "counties": [ + { + "name": "船山区", + "regionId": 510903 + }, + { + "name": "安居区", + "regionId": 510904 + }, + { + "name": "蓬溪县", + "regionId": 510921 + }, + { + "name": "大英县", + "regionId": 510923 + }, + { + "name": "射洪市", + "regionId": 510981 + } + ], + "name": "遂宁市", + "regionId": 510900 + }, + { + "counties": [ + { + "name": "市中区", + "regionId": 511002 + }, + { + "name": "东兴区", + "regionId": 511011 + }, + { + "name": "威远县", + "regionId": 511024 + }, + { + "name": "资中县", + "regionId": 511025 + }, + { + "name": "隆昌市", + "regionId": 511083 + } + ], + "name": "内江市", + "regionId": 511000 + }, + { + "counties": [ + { + "name": "市中区", + "regionId": 511102 + }, + { + "name": "沙湾区", + "regionId": 511111 + }, + { + "name": "五通桥区", + "regionId": 511112 + }, + { + "name": "金口河区", + "regionId": 511113 + }, + { + "name": "犍为县", + "regionId": 511123 + }, + { + "name": "井研县", + "regionId": 511124 + }, + { + "name": "夹江县", + "regionId": 511126 + }, + { + "name": "沐川县", + "regionId": 511129 + }, + { + "name": "峨边彝族自治县", + "regionId": 511132 + }, + { + "name": "马边彝族自治县", + "regionId": 511133 + }, + { + "name": "峨眉山市", + "regionId": 511181 + } + ], + "name": "乐山市", + "regionId": 511100 + }, + { + "counties": [ + { + "name": "顺庆区", + "regionId": 511302 + }, + { + "name": "高坪区", + "regionId": 511303 + }, + { + "name": "嘉陵区", + "regionId": 511304 + }, + { + "name": "南部县", + "regionId": 511321 + }, + { + "name": "营山县", + "regionId": 511322 + }, + { + "name": "蓬安县", + "regionId": 511323 + }, + { + "name": "仪陇县", + "regionId": 511324 + }, + { + "name": "西充县", + "regionId": 511325 + }, + { + "name": "阆中市", + "regionId": 511381 + } + ], + "name": "南充市", + "regionId": 511300 + }, + { + "counties": [ + { + "name": "东坡区", + "regionId": 511402 + }, + { + "name": "彭山区", + "regionId": 511403 + }, + { + "name": "仁寿县", + "regionId": 511421 + }, + { + "name": "洪雅县", + "regionId": 511423 + }, + { + "name": "丹棱县", + "regionId": 511424 + }, + { + "name": "青神县", + "regionId": 511425 + } + ], + "name": "眉山市", + "regionId": 511400 + }, + { + "counties": [ + { + "name": "翠屏区", + "regionId": 511502 + }, + { + "name": "南溪区", + "regionId": 511503 + }, + { + "name": "叙州区", + "regionId": 511504 + }, + { + "name": "江安县", + "regionId": 511523 + }, + { + "name": "长宁县", + "regionId": 511524 + }, + { + "name": "高县", + "regionId": 511525 + }, + { + "name": "珙县", + "regionId": 511526 + }, + { + "name": "筠连县", + "regionId": 511527 + }, + { + "name": "兴文县", + "regionId": 511528 + }, + { + "name": "屏山县", + "regionId": 511529 + } + ], + "name": "宜宾市", + "regionId": 511500 + }, + { + "counties": [ + { + "name": "广安区", + "regionId": 511602 + }, + { + "name": "前锋区", + "regionId": 511603 + }, + { + "name": "岳池县", + "regionId": 511621 + }, + { + "name": "武胜县", + "regionId": 511622 + }, + { + "name": "邻水县", + "regionId": 511623 + }, + { + "name": "华蓥市", + "regionId": 511681 + } + ], + "name": "广安市", + "regionId": 511600 + }, + { + "counties": [ + { + "name": "通川区", + "regionId": 511702 + }, + { + "name": "达川区", + "regionId": 511703 + }, + { + "name": "宣汉县", + "regionId": 511722 + }, + { + "name": "开江县", + "regionId": 511723 + }, + { + "name": "大竹县", + "regionId": 511724 + }, + { + "name": "渠县", + "regionId": 511725 + }, + { + "name": "万源市", + "regionId": 511781 + } + ], + "name": "达州市", + "regionId": 511700 + }, + { + "counties": [ + { + "name": "雨城区", + "regionId": 511802 + }, + { + "name": "名山区", + "regionId": 511803 + }, + { + "name": "荥经县", + "regionId": 511822 + }, + { + "name": "汉源县", + "regionId": 511823 + }, + { + "name": "石棉县", + "regionId": 511824 + }, + { + "name": "天全县", + "regionId": 511825 + }, + { + "name": "芦山县", + "regionId": 511826 + }, + { + "name": "宝兴县", + "regionId": 511827 + } + ], + "name": "雅安市", + "regionId": 511800 + }, + { + "counties": [ + { + "name": "巴州区", + "regionId": 511902 + }, + { + "name": "恩阳区", + "regionId": 511903 + }, + { + "name": "通江县", + "regionId": 511921 + }, + { + "name": "南江县", + "regionId": 511922 + }, + { + "name": "平昌县", + "regionId": 511923 + } + ], + "name": "巴中市", + "regionId": 511900 + }, + { + "counties": [ + { + "name": "雁江区", + "regionId": 512002 + }, + { + "name": "安岳县", + "regionId": 512021 + }, + { + "name": "乐至县", + "regionId": 512022 + } + ], + "name": "资阳市", + "regionId": 512000 + }, + { + "counties": [ + { + "name": "马尔康市", + "regionId": 513201 + }, + { + "name": "汶川县", + "regionId": 513221 + }, + { + "name": "理县", + "regionId": 513222 + }, + { + "name": "茂县", + "regionId": 513223 + }, + { + "name": "松潘县", + "regionId": 513224 + }, + { + "name": "九寨沟县", + "regionId": 513225 + }, + { + "name": "金川县", + "regionId": 513226 + }, + { + "name": "小金县", + "regionId": 513227 + }, + { + "name": "黑水县", + "regionId": 513228 + }, + { + "name": "壤塘县", + "regionId": 513230 + }, + { + "name": "阿坝县", + "regionId": 513231 + }, + { + "name": "若尔盖县", + "regionId": 513232 + }, + { + "name": "红原县", + "regionId": 513233 + } + ], + "name": "阿坝藏族羌族自治州", + "regionId": 513200 + }, + { + "counties": [ + { + "name": "康定市", + "regionId": 513301 + }, + { + "name": "泸定县", + "regionId": 513322 + }, + { + "name": "丹巴县", + "regionId": 513323 + }, + { + "name": "九龙县", + "regionId": 513324 + }, + { + "name": "雅江县", + "regionId": 513325 + }, + { + "name": "道孚县", + "regionId": 513326 + }, + { + "name": "炉霍县", + "regionId": 513327 + }, + { + "name": "甘孜县", + "regionId": 513328 + }, + { + "name": "新龙县", + "regionId": 513329 + }, + { + "name": "德格县", + "regionId": 513330 + }, + { + "name": "白玉县", + "regionId": 513331 + }, + { + "name": "石渠县", + "regionId": 513332 + }, + { + "name": "色达县", + "regionId": 513333 + }, + { + "name": "理塘县", + "regionId": 513334 + }, + { + "name": "巴塘县", + "regionId": 513335 + }, + { + "name": "乡城县", + "regionId": 513336 + }, + { + "name": "稻城县", + "regionId": 513337 + }, + { + "name": "得荣县", + "regionId": 513338 + } + ], + "name": "甘孜藏族自治州", + "regionId": 513300 + }, + { + "counties": [ + { + "name": "西昌市", + "regionId": 513401 + }, + { + "name": "会理市", + "regionId": 513402 + }, + { + "name": "木里藏族自治县", + "regionId": 513422 + }, + { + "name": "盐源县", + "regionId": 513423 + }, + { + "name": "德昌县", + "regionId": 513424 + }, + { + "name": "会东县", + "regionId": 513426 + }, + { + "name": "宁南县", + "regionId": 513427 + }, + { + "name": "普格县", + "regionId": 513428 + }, + { + "name": "布拖县", + "regionId": 513429 + }, + { + "name": "金阳县", + "regionId": 513430 + }, + { + "name": "昭觉县", + "regionId": 513431 + }, + { + "name": "喜德县", + "regionId": 513432 + }, + { + "name": "冕宁县", + "regionId": 513433 + }, + { + "name": "越西县", + "regionId": 513434 + }, + { + "name": "甘洛县", + "regionId": 513435 + }, + { + "name": "美姑县", + "regionId": 513436 + }, + { + "name": "雷波县", + "regionId": 513437 + } + ], + "name": "凉山彝族自治州", + "regionId": 513400 + } + ], + "name": "四川省", + "regionId": 510000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "南明区", + "regionId": 520102 + }, + { + "name": "云岩区", + "regionId": 520103 + }, + { + "name": "花溪区", + "regionId": 520111 + }, + { + "name": "乌当区", + "regionId": 520112 + }, + { + "name": "白云区", + "regionId": 520113 + }, + { + "name": "观山湖区", + "regionId": 520115 + }, + { + "name": "开阳县", + "regionId": 520121 + }, + { + "name": "息烽县", + "regionId": 520122 + }, + { + "name": "修文县", + "regionId": 520123 + }, + { + "name": "清镇市", + "regionId": 520181 + } + ], + "name": "贵阳市", + "regionId": 520100 + }, + { + "counties": [ + { + "name": "钟山区", + "regionId": 520201 + }, + { + "name": "六枝特区", + "regionId": 520203 + }, + { + "name": "水城区", + "regionId": 520204 + }, + { + "name": "盘州市", + "regionId": 520281 + } + ], + "name": "六盘水市", + "regionId": 520200 + }, + { + "counties": [ + { + "name": "红花岗区", + "regionId": 520302 + }, + { + "name": "汇川区", + "regionId": 520303 + }, + { + "name": "播州区", + "regionId": 520304 + }, + { + "name": "桐梓县", + "regionId": 520322 + }, + { + "name": "绥阳县", + "regionId": 520323 + }, + { + "name": "正安县", + "regionId": 520324 + }, + { + "name": "道真仡佬族苗族自治县", + "regionId": 520325 + }, + { + "name": "务川仡佬族苗族自治县", + "regionId": 520326 + }, + { + "name": "凤冈县", + "regionId": 520327 + }, + { + "name": "湄潭县", + "regionId": 520328 + }, + { + "name": "余庆县", + "regionId": 520329 + }, + { + "name": "习水县", + "regionId": 520330 + }, + { + "name": "赤水市", + "regionId": 520381 + }, + { + "name": "仁怀市", + "regionId": 520382 + } + ], + "name": "遵义市", + "regionId": 520300 + }, + { + "counties": [ + { + "name": "西秀区", + "regionId": 520402 + }, + { + "name": "平坝区", + "regionId": 520403 + }, + { + "name": "普定县", + "regionId": 520422 + }, + { + "name": "镇宁布依族苗族自治县", + "regionId": 520423 + }, + { + "name": "关岭布依族苗族自治县", + "regionId": 520424 + }, + { + "name": "紫云苗族布依族自治县", + "regionId": 520425 + } + ], + "name": "安顺市", + "regionId": 520400 + }, + { + "counties": [ + { + "name": "七星关区", + "regionId": 520502 + }, + { + "name": "大方县", + "regionId": 520521 + }, + { + "name": "金沙县", + "regionId": 520523 + }, + { + "name": "织金县", + "regionId": 520524 + }, + { + "name": "纳雍县", + "regionId": 520525 + }, + { + "name": "威宁彝族回族苗族自治县", + "regionId": 520526 + }, + { + "name": "赫章县", + "regionId": 520527 + }, + { + "name": "黔西市", + "regionId": 520581 + } + ], + "name": "毕节市", + "regionId": 520500 + }, + { + "counties": [ + { + "name": "碧江区", + "regionId": 520602 + }, + { + "name": "万山区", + "regionId": 520603 + }, + { + "name": "江口县", + "regionId": 520621 + }, + { + "name": "玉屏侗族自治县", + "regionId": 520622 + }, + { + "name": "石阡县", + "regionId": 520623 + }, + { + "name": "思南县", + "regionId": 520624 + }, + { + "name": "印江土家族苗族自治县", + "regionId": 520625 + }, + { + "name": "德江县", + "regionId": 520626 + }, + { + "name": "沿河土家族自治县", + "regionId": 520627 + }, + { + "name": "松桃苗族自治县", + "regionId": 520628 + } + ], + "name": "铜仁市", + "regionId": 520600 + }, + { + "counties": [ + { + "name": "兴义市", + "regionId": 522301 + }, + { + "name": "兴仁市", + "regionId": 522302 + }, + { + "name": "普安县", + "regionId": 522323 + }, + { + "name": "晴隆县", + "regionId": 522324 + }, + { + "name": "贞丰县", + "regionId": 522325 + }, + { + "name": "望谟县", + "regionId": 522326 + }, + { + "name": "册亨县", + "regionId": 522327 + }, + { + "name": "安龙县", + "regionId": 522328 + } + ], + "name": "黔西南布依族苗族自治州", + "regionId": 522300 + }, + { + "counties": [ + { + "name": "凯里市", + "regionId": 522601 + }, + { + "name": "黄平县", + "regionId": 522622 + }, + { + "name": "施秉县", + "regionId": 522623 + }, + { + "name": "三穗县", + "regionId": 522624 + }, + { + "name": "镇远县", + "regionId": 522625 + }, + { + "name": "岑巩县", + "regionId": 522626 + }, + { + "name": "天柱县", + "regionId": 522627 + }, + { + "name": "锦屏县", + "regionId": 522628 + }, + { + "name": "剑河县", + "regionId": 522629 + }, + { + "name": "台江县", + "regionId": 522630 + }, + { + "name": "黎平县", + "regionId": 522631 + }, + { + "name": "榕江县", + "regionId": 522632 + }, + { + "name": "从江县", + "regionId": 522633 + }, + { + "name": "雷山县", + "regionId": 522634 + }, + { + "name": "麻江县", + "regionId": 522635 + }, + { + "name": "丹寨县", + "regionId": 522636 + } + ], + "name": "黔东南苗族侗族自治州", + "regionId": 522600 + }, + { + "counties": [ + { + "name": "都匀市", + "regionId": 522701 + }, + { + "name": "福泉市", + "regionId": 522702 + }, + { + "name": "荔波县", + "regionId": 522722 + }, + { + "name": "贵定县", + "regionId": 522723 + }, + { + "name": "瓮安县", + "regionId": 522725 + }, + { + "name": "独山县", + "regionId": 522726 + }, + { + "name": "平塘县", + "regionId": 522727 + }, + { + "name": "罗甸县", + "regionId": 522728 + }, + { + "name": "长顺县", + "regionId": 522729 + }, + { + "name": "龙里县", + "regionId": 522730 + }, + { + "name": "惠水县", + "regionId": 522731 + }, + { + "name": "三都水族自治县", + "regionId": 522732 + } + ], + "name": "黔南布依族苗族自治州", + "regionId": 522700 + } + ], + "name": "贵州省", + "regionId": 520000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "五华区", + "regionId": 530102 + }, + { + "name": "盘龙区", + "regionId": 530103 + }, + { + "name": "官渡区", + "regionId": 530111 + }, + { + "name": "西山区", + "regionId": 530112 + }, + { + "name": "东川区", + "regionId": 530113 + }, + { + "name": "呈贡区", + "regionId": 530114 + }, + { + "name": "晋宁区", + "regionId": 530115 + }, + { + "name": "富民县", + "regionId": 530124 + }, + { + "name": "宜良县", + "regionId": 530125 + }, + { + "name": "石林彝族自治县", + "regionId": 530126 + }, + { + "name": "嵩明县", + "regionId": 530127 + }, + { + "name": "禄劝彝族苗族自治县", + "regionId": 530128 + }, + { + "name": "寻甸回族彝族自治县", + "regionId": 530129 + }, + { + "name": "安宁市", + "regionId": 530181 + } + ], + "name": "昆明市", + "regionId": 530100 + }, + { + "counties": [ + { + "name": "麒麟区", + "regionId": 530302 + }, + { + "name": "沾益区", + "regionId": 530303 + }, + { + "name": "马龙区", + "regionId": 530304 + }, + { + "name": "陆良县", + "regionId": 530322 + }, + { + "name": "师宗县", + "regionId": 530323 + }, + { + "name": "罗平县", + "regionId": 530324 + }, + { + "name": "富源县", + "regionId": 530325 + }, + { + "name": "会泽县", + "regionId": 530326 + }, + { + "name": "宣威市", + "regionId": 530381 + } + ], + "name": "曲靖市", + "regionId": 530300 + }, + { + "counties": [ + { + "name": "红塔区", + "regionId": 530402 + }, + { + "name": "江川区", + "regionId": 530403 + }, + { + "name": "通海县", + "regionId": 530423 + }, + { + "name": "华宁县", + "regionId": 530424 + }, + { + "name": "易门县", + "regionId": 530425 + }, + { + "name": "峨山彝族自治县", + "regionId": 530426 + }, + { + "name": "新平彝族傣族自治县", + "regionId": 530427 + }, + { + "name": "元江哈尼族彝族傣族自治县", + "regionId": 530428 + }, + { + "name": "澄江市", + "regionId": 530481 + } + ], + "name": "玉溪市", + "regionId": 530400 + }, + { + "counties": [ + { + "name": "隆阳区", + "regionId": 530502 + }, + { + "name": "施甸县", + "regionId": 530521 + }, + { + "name": "龙陵县", + "regionId": 530523 + }, + { + "name": "昌宁县", + "regionId": 530524 + }, + { + "name": "腾冲市", + "regionId": 530581 + } + ], + "name": "保山市", + "regionId": 530500 + }, + { + "counties": [ + { + "name": "昭阳区", + "regionId": 530602 + }, + { + "name": "鲁甸县", + "regionId": 530621 + }, + { + "name": "巧家县", + "regionId": 530622 + }, + { + "name": "盐津县", + "regionId": 530623 + }, + { + "name": "大关县", + "regionId": 530624 + }, + { + "name": "永善县", + "regionId": 530625 + }, + { + "name": "绥江县", + "regionId": 530626 + }, + { + "name": "镇雄县", + "regionId": 530627 + }, + { + "name": "彝良县", + "regionId": 530628 + }, + { + "name": "威信县", + "regionId": 530629 + }, + { + "name": "水富市", + "regionId": 530681 + } + ], + "name": "昭通市", + "regionId": 530600 + }, + { + "counties": [ + { + "name": "古城区", + "regionId": 530702 + }, + { + "name": "玉龙纳西族自治县", + "regionId": 530721 + }, + { + "name": "永胜县", + "regionId": 530722 + }, + { + "name": "华坪县", + "regionId": 530723 + }, + { + "name": "宁蒗彝族自治县", + "regionId": 530724 + } + ], + "name": "丽江市", + "regionId": 530700 + }, + { + "counties": [ + { + "name": "思茅区", + "regionId": 530802 + }, + { + "name": "宁洱哈尼族彝族自治县", + "regionId": 530821 + }, + { + "name": "墨江哈尼族自治县", + "regionId": 530822 + }, + { + "name": "景东彝族自治县", + "regionId": 530823 + }, + { + "name": "景谷傣族彝族自治县", + "regionId": 530824 + }, + { + "name": "镇沅彝族哈尼族拉祜族自治县", + "regionId": 530825 + }, + { + "name": "江城哈尼族彝族自治县", + "regionId": 530826 + }, + { + "name": "孟连傣族拉祜族佤族自治县", + "regionId": 530827 + }, + { + "name": "澜沧拉祜族自治县", + "regionId": 530828 + }, + { + "name": "西盟佤族自治县", + "regionId": 530829 + } + ], + "name": "普洱市", + "regionId": 530800 + }, + { + "counties": [ + { + "name": "临翔区", + "regionId": 530902 + }, + { + "name": "凤庆县", + "regionId": 530921 + }, + { + "name": "云县", + "regionId": 530922 + }, + { + "name": "永德县", + "regionId": 530923 + }, + { + "name": "镇康县", + "regionId": 530924 + }, + { + "name": "双江拉祜族佤族布朗族傣族自治县", + "regionId": 530925 + }, + { + "name": "耿马傣族佤族自治县", + "regionId": 530926 + }, + { + "name": "沧源佤族自治县", + "regionId": 530927 + } + ], + "name": "临沧市", + "regionId": 530900 + }, + { + "counties": [ + { + "name": "楚雄市", + "regionId": 532301 + }, + { + "name": "禄丰市", + "regionId": 532302 + }, + { + "name": "双柏县", + "regionId": 532322 + }, + { + "name": "牟定县", + "regionId": 532323 + }, + { + "name": "南华县", + "regionId": 532324 + }, + { + "name": "姚安县", + "regionId": 532325 + }, + { + "name": "大姚县", + "regionId": 532326 + }, + { + "name": "永仁县", + "regionId": 532327 + }, + { + "name": "元谋县", + "regionId": 532328 + }, + { + "name": "武定县", + "regionId": 532329 + } + ], + "name": "楚雄彝族自治州", + "regionId": 532300 + }, + { + "counties": [ + { + "name": "个旧市", + "regionId": 532501 + }, + { + "name": "开远市", + "regionId": 532502 + }, + { + "name": "蒙自市", + "regionId": 532503 + }, + { + "name": "弥勒市", + "regionId": 532504 + }, + { + "name": "屏边苗族自治县", + "regionId": 532523 + }, + { + "name": "建水县", + "regionId": 532524 + }, + { + "name": "石屏县", + "regionId": 532525 + }, + { + "name": "泸西县", + "regionId": 532527 + }, + { + "name": "元阳县", + "regionId": 532528 + }, + { + "name": "红河县", + "regionId": 532529 + }, + { + "name": "金平苗族瑶族傣族自治县", + "regionId": 532530 + }, + { + "name": "绿春县", + "regionId": 532531 + }, + { + "name": "河口瑶族自治县", + "regionId": 532532 + } + ], + "name": "红河哈尼族彝族自治州", + "regionId": 532500 + }, + { + "counties": [ + { + "name": "文山市", + "regionId": 532601 + }, + { + "name": "砚山县", + "regionId": 532622 + }, + { + "name": "西畴县", + "regionId": 532623 + }, + { + "name": "麻栗坡县", + "regionId": 532624 + }, + { + "name": "马关县", + "regionId": 532625 + }, + { + "name": "丘北县", + "regionId": 532626 + }, + { + "name": "广南县", + "regionId": 532627 + }, + { + "name": "富宁县", + "regionId": 532628 + } + ], + "name": "文山壮族苗族自治州", + "regionId": 532600 + }, + { + "counties": [ + { + "name": "景洪市", + "regionId": 532801 + }, + { + "name": "勐海县", + "regionId": 532822 + }, + { + "name": "勐腊县", + "regionId": 532823 + } + ], + "name": "西双版纳傣族自治州", + "regionId": 532800 + }, + { + "counties": [ + { + "name": "大理市", + "regionId": 532901 + }, + { + "name": "漾濞彝族自治县", + "regionId": 532922 + }, + { + "name": "祥云县", + "regionId": 532923 + }, + { + "name": "宾川县", + "regionId": 532924 + }, + { + "name": "弥渡县", + "regionId": 532925 + }, + { + "name": "南涧彝族自治县", + "regionId": 532926 + }, + { + "name": "巍山彝族回族自治县", + "regionId": 532927 + }, + { + "name": "永平县", + "regionId": 532928 + }, + { + "name": "云龙县", + "regionId": 532929 + }, + { + "name": "洱源县", + "regionId": 532930 + }, + { + "name": "剑川县", + "regionId": 532931 + }, + { + "name": "鹤庆县", + "regionId": 532932 + } + ], + "name": "大理白族自治州", + "regionId": 532900 + }, + { + "counties": [ + { + "name": "瑞丽市", + "regionId": 533102 + }, + { + "name": "芒市", + "regionId": 533103 + }, + { + "name": "梁河县", + "regionId": 533122 + }, + { + "name": "盈江县", + "regionId": 533123 + }, + { + "name": "陇川县", + "regionId": 533124 + } + ], + "name": "德宏傣族景颇族自治州", + "regionId": 533100 + }, + { + "counties": [ + { + "name": "泸水市", + "regionId": 533301 + }, + { + "name": "福贡县", + "regionId": 533323 + }, + { + "name": "贡山独龙族怒族自治县", + "regionId": 533324 + }, + { + "name": "兰坪白族普米族自治县", + "regionId": 533325 + } + ], + "name": "怒江傈僳族自治州", + "regionId": 533300 + }, + { + "counties": [ + { + "name": "香格里拉市", + "regionId": 533401 + }, + { + "name": "德钦县", + "regionId": 533422 + }, + { + "name": "维西傈僳族自治县", + "regionId": 533423 + } + ], + "name": "迪庆藏族自治州", + "regionId": 533400 + } + ], + "name": "云南省", + "regionId": 530000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "城关区", + "regionId": 540102 + }, + { + "name": "堆龙德庆区", + "regionId": 540103 + }, + { + "name": "达孜区", + "regionId": 540104 + }, + { + "name": "林周县", + "regionId": 540121 + }, + { + "name": "当雄县", + "regionId": 540122 + }, + { + "name": "尼木县", + "regionId": 540123 + }, + { + "name": "曲水县", + "regionId": 540124 + }, + { + "name": "墨竹工卡县", + "regionId": 540127 + } + ], + "name": "拉萨市", + "regionId": 540100 + }, + { + "counties": [ + { + "name": "桑珠孜区", + "regionId": 540202 + }, + { + "name": "南木林县", + "regionId": 540221 + }, + { + "name": "江孜县", + "regionId": 540222 + }, + { + "name": "定日县", + "regionId": 540223 + }, + { + "name": "萨迦县", + "regionId": 540224 + }, + { + "name": "拉孜县", + "regionId": 540225 + }, + { + "name": "昂仁县", + "regionId": 540226 + }, + { + "name": "谢通门县", + "regionId": 540227 + }, + { + "name": "白朗县", + "regionId": 540228 + }, + { + "name": "仁布县", + "regionId": 540229 + }, + { + "name": "康马县", + "regionId": 540230 + }, + { + "name": "定结县", + "regionId": 540231 + }, + { + "name": "仲巴县", + "regionId": 540232 + }, + { + "name": "亚东县", + "regionId": 540233 + }, + { + "name": "吉隆县", + "regionId": 540234 + }, + { + "name": "聂拉木县", + "regionId": 540235 + }, + { + "name": "萨嘎县", + "regionId": 540236 + }, + { + "name": "岗巴县", + "regionId": 540237 + } + ], + "name": "日喀则市", + "regionId": 540200 + }, + { + "counties": [ + { + "name": "卡若区", + "regionId": 540302 + }, + { + "name": "江达县", + "regionId": 540321 + }, + { + "name": "贡觉县", + "regionId": 540322 + }, + { + "name": "类乌齐县", + "regionId": 540323 + }, + { + "name": "丁青县", + "regionId": 540324 + }, + { + "name": "察雅县", + "regionId": 540325 + }, + { + "name": "八宿县", + "regionId": 540326 + }, + { + "name": "左贡县", + "regionId": 540327 + }, + { + "name": "芒康县", + "regionId": 540328 + }, + { + "name": "洛隆县", + "regionId": 540329 + }, + { + "name": "边坝县", + "regionId": 540330 + } + ], + "name": "昌都市", + "regionId": 540300 + }, + { + "counties": [ + { + "name": "巴宜区", + "regionId": 540402 + }, + { + "name": "工布江达县", + "regionId": 540421 + }, + { + "name": "墨脱县", + "regionId": 540423 + }, + { + "name": "波密县", + "regionId": 540424 + }, + { + "name": "察隅县", + "regionId": 540425 + }, + { + "name": "朗县", + "regionId": 540426 + }, + { + "name": "米林市", + "regionId": 540481 + } + ], + "name": "林芝市", + "regionId": 540400 + }, + { + "counties": [ + { + "name": "乃东区", + "regionId": 540502 + }, + { + "name": "扎囊县", + "regionId": 540521 + }, + { + "name": "贡嘎县", + "regionId": 540522 + }, + { + "name": "桑日县", + "regionId": 540523 + }, + { + "name": "琼结县", + "regionId": 540524 + }, + { + "name": "曲松县", + "regionId": 540525 + }, + { + "name": "措美县", + "regionId": 540526 + }, + { + "name": "洛扎县", + "regionId": 540527 + }, + { + "name": "加查县", + "regionId": 540528 + }, + { + "name": "隆子县", + "regionId": 540529 + }, + { + "name": "浪卡子县", + "regionId": 540531 + }, + { + "name": "错那市", + "regionId": 540581 + } + ], + "name": "山南市", + "regionId": 540500 + }, + { + "counties": [ + { + "name": "色尼区", + "regionId": 540602 + }, + { + "name": "嘉黎县", + "regionId": 540621 + }, + { + "name": "比如县", + "regionId": 540622 + }, + { + "name": "聂荣县", + "regionId": 540623 + }, + { + "name": "安多县", + "regionId": 540624 + }, + { + "name": "申扎县", + "regionId": 540625 + }, + { + "name": "索县", + "regionId": 540626 + }, + { + "name": "班戈县", + "regionId": 540627 + }, + { + "name": "巴青县", + "regionId": 540628 + }, + { + "name": "尼玛县", + "regionId": 540629 + }, + { + "name": "双湖县", + "regionId": 540630 + } + ], + "name": "那曲市", + "regionId": 540600 + }, + { + "counties": [ + { + "name": "普兰县", + "regionId": 542521 + }, + { + "name": "札达县", + "regionId": 542522 + }, + { + "name": "噶尔县", + "regionId": 542523 + }, + { + "name": "日土县", + "regionId": 542524 + }, + { + "name": "革吉县", + "regionId": 542525 + }, + { + "name": "改则县", + "regionId": 542526 + }, + { + "name": "措勤县", + "regionId": 542527 + } + ], + "name": "阿里地区", + "regionId": 542500 + } + ], + "name": "西藏自治区", + "regionId": 540000 + } + ] + }, + { + "index": 7, + "part": "港澳台", + "provinces": [ + { + "cities": [ + { + "counties": [ + { + "name": "中正区", + "regionId": 710101 + }, + { + "name": "大同区", + "regionId": 710102 + }, + { + "name": "中山区", + "regionId": 710103 + }, + { + "name": "松山区", + "regionId": 710104 + }, + { + "name": "大安区", + "regionId": 710105 + }, + { + "name": "万华区", + "regionId": 710106 + }, + { + "name": "信义区", + "regionId": 710107 + }, + { + "name": "士林区", + "regionId": 710108 + }, + { + "name": "北投区", + "regionId": 710109 + }, + { + "name": "内湖区", + "regionId": 710110 + }, + { + "name": "南港区", + "regionId": 710111 + }, + { + "name": "文山区", + "regionId": 710112 + }, + { + "name": "其它区", + "regionId": 710199 + } + ], + "name": "台北市", + "regionId": 710100 + }, + { + "counties": [ + { + "name": "新兴区", + "regionId": 710201 + }, + { + "name": "前金区", + "regionId": 710202 + }, + { + "name": "芩雅区", + "regionId": 710203 + }, + { + "name": "盐埕区", + "regionId": 710204 + }, + { + "name": "鼓山区", + "regionId": 710205 + }, + { + "name": "旗津区", + "regionId": 710206 + }, + { + "name": "前镇区", + "regionId": 710207 + }, + { + "name": "三民区", + "regionId": 710208 + }, + { + "name": "左营区", + "regionId": 710209 + }, + { + "name": "楠梓区", + "regionId": 710210 + }, + { + "name": "小港区", + "regionId": 710211 + }, + { + "name": "苓雅区", + "regionId": 710241 + }, + { + "name": "仁武区", + "regionId": 710242 + }, + { + "name": "大社区", + "regionId": 710243 + }, + { + "name": "冈山区", + "regionId": 710244 + }, + { + "name": "路竹区", + "regionId": 710245 + }, + { + "name": "阿莲区", + "regionId": 710246 + }, + { + "name": "田寮区", + "regionId": 710247 + }, + { + "name": "燕巢区", + "regionId": 710248 + }, + { + "name": "桥头区", + "regionId": 710249 + }, + { + "name": "梓官区", + "regionId": 710250 + }, + { + "name": "弥陀区", + "regionId": 710251 + }, + { + "name": "永安区", + "regionId": 710252 + }, + { + "name": "湖内区", + "regionId": 710253 + }, + { + "name": "凤山区", + "regionId": 710254 + }, + { + "name": "大寮区", + "regionId": 710255 + }, + { + "name": "林园区", + "regionId": 710256 + }, + { + "name": "鸟松区", + "regionId": 710257 + }, + { + "name": "大树区", + "regionId": 710258 + }, + { + "name": "旗山区", + "regionId": 710259 + }, + { + "name": "美浓区", + "regionId": 710260 + }, + { + "name": "六龟区", + "regionId": 710261 + }, + { + "name": "内门区", + "regionId": 710262 + }, + { + "name": "杉林区", + "regionId": 710263 + }, + { + "name": "甲仙区", + "regionId": 710264 + }, + { + "name": "桃源区", + "regionId": 710265 + }, + { + "name": "那玛夏区", + "regionId": 710266 + }, + { + "name": "茂林区", + "regionId": 710267 + }, + { + "name": "茄萣区", + "regionId": 710268 + }, + { + "name": "其它区", + "regionId": 710299 + } + ], + "name": "高雄市", + "regionId": 710200 + }, + { + "counties": [ + { + "name": "中西区", + "regionId": 710301 + }, + { + "name": "东区", + "regionId": 710302 + }, + { + "name": "南区", + "regionId": 710303 + }, + { + "name": "北区", + "regionId": 710304 + }, + { + "name": "安平区", + "regionId": 710305 + }, + { + "name": "安南区", + "regionId": 710306 + }, + { + "name": "永康区", + "regionId": 710339 + }, + { + "name": "归仁区", + "regionId": 710340 + }, + { + "name": "新化区", + "regionId": 710341 + }, + { + "name": "左镇区", + "regionId": 710342 + }, + { + "name": "玉井区", + "regionId": 710343 + }, + { + "name": "楠西区", + "regionId": 710344 + }, + { + "name": "南化区", + "regionId": 710345 + }, + { + "name": "仁德区", + "regionId": 710346 + }, + { + "name": "关庙区", + "regionId": 710347 + }, + { + "name": "龙崎区", + "regionId": 710348 + }, + { + "name": "官田区", + "regionId": 710349 + }, + { + "name": "麻豆区", + "regionId": 710350 + }, + { + "name": "佳里区", + "regionId": 710351 + }, + { + "name": "西港区", + "regionId": 710352 + }, + { + "name": "七股区", + "regionId": 710353 + }, + { + "name": "将军区", + "regionId": 710354 + }, + { + "name": "学甲区", + "regionId": 710355 + }, + { + "name": "北门区", + "regionId": 710356 + }, + { + "name": "新营区", + "regionId": 710357 + }, + { + "name": "后壁区", + "regionId": 710358 + }, + { + "name": "白河区", + "regionId": 710359 + }, + { + "name": "东山区", + "regionId": 710360 + }, + { + "name": "六甲区", + "regionId": 710361 + }, + { + "name": "下营区", + "regionId": 710362 + }, + { + "name": "柳营区", + "regionId": 710363 + }, + { + "name": "盐水区", + "regionId": 710364 + }, + { + "name": "善化区", + "regionId": 710365 + }, + { + "name": "大内区", + "regionId": 710366 + }, + { + "name": "山上区", + "regionId": 710367 + }, + { + "name": "新市区", + "regionId": 710368 + }, + { + "name": "安定区", + "regionId": 710369 + }, + { + "name": "其它区", + "regionId": 710399 + } + ], + "name": "台南市", + "regionId": 710300 + }, + { + "counties": [ + { + "name": "中区", + "regionId": 710401 + }, + { + "name": "东区", + "regionId": 710402 + }, + { + "name": "南区", + "regionId": 710403 + }, + { + "name": "西区", + "regionId": 710404 + }, + { + "name": "北区", + "regionId": 710405 + }, + { + "name": "北屯区", + "regionId": 710406 + }, + { + "name": "西屯区", + "regionId": 710407 + }, + { + "name": "南屯区", + "regionId": 710408 + }, + { + "name": "太平区", + "regionId": 710431 + }, + { + "name": "大里区", + "regionId": 710432 + }, + { + "name": "雾峰区", + "regionId": 710433 + }, + { + "name": "乌日区", + "regionId": 710434 + }, + { + "name": "丰原区", + "regionId": 710435 + }, + { + "name": "后里区", + "regionId": 710436 + }, + { + "name": "石冈区", + "regionId": 710437 + }, + { + "name": "东势区", + "regionId": 710438 + }, + { + "name": "和平区", + "regionId": 710439 + }, + { + "name": "新社区", + "regionId": 710440 + }, + { + "name": "潭子区", + "regionId": 710441 + }, + { + "name": "大雅区", + "regionId": 710442 + }, + { + "name": "神冈区", + "regionId": 710443 + }, + { + "name": "大肚区", + "regionId": 710444 + }, + { + "name": "沙鹿区", + "regionId": 710445 + }, + { + "name": "龙井区", + "regionId": 710446 + }, + { + "name": "梧栖区", + "regionId": 710447 + }, + { + "name": "清水区", + "regionId": 710448 + }, + { + "name": "大甲区", + "regionId": 710449 + }, + { + "name": "外埔区", + "regionId": 710450 + }, + { + "name": "大安区", + "regionId": 710451 + }, + { + "name": "其它区", + "regionId": 710499 + } + ], + "name": "台中市", + "regionId": 710400 + }, + { + "counties": [ + { + "name": "金沙镇", + "regionId": 710507 + }, + { + "name": "金湖镇", + "regionId": 710508 + }, + { + "name": "金宁乡", + "regionId": 710509 + }, + { + "name": "金城镇", + "regionId": 710510 + }, + { + "name": "烈屿乡", + "regionId": 710511 + }, + { + "name": "乌坵乡", + "regionId": 710512 + } + ], + "name": "金门县", + "regionId": 710500 + }, + { + "counties": [ + { + "name": "南投市", + "regionId": 710614 + }, + { + "name": "中寮乡", + "regionId": 710615 + }, + { + "name": "草屯镇", + "regionId": 710616 + }, + { + "name": "国姓乡", + "regionId": 710617 + }, + { + "name": "埔里镇", + "regionId": 710618 + }, + { + "name": "仁爱乡", + "regionId": 710619 + }, + { + "name": "名间乡", + "regionId": 710620 + }, + { + "name": "集集镇", + "regionId": 710621 + }, + { + "name": "水里乡", + "regionId": 710622 + }, + { + "name": "鱼池乡", + "regionId": 710623 + }, + { + "name": "信义乡", + "regionId": 710624 + }, + { + "name": "竹山镇", + "regionId": 710625 + }, + { + "name": "鹿谷乡", + "regionId": 710626 + } + ], + "name": "南投县", + "regionId": 710600 + }, + { + "counties": [ + { + "name": "仁爱区", + "regionId": 710701 + }, + { + "name": "信义区", + "regionId": 710702 + }, + { + "name": "中正区", + "regionId": 710703 + }, + { + "name": "中山区", + "regionId": 710704 + }, + { + "name": "安乐区", + "regionId": 710705 + }, + { + "name": "暖暖区", + "regionId": 710706 + }, + { + "name": "七堵区", + "regionId": 710707 + }, + { + "name": "其它区", + "regionId": 710799 + } + ], + "name": "基隆市", + "regionId": 710700 + }, + { + "counties": [ + { + "name": "东区", + "regionId": 710801 + }, + { + "name": "北区", + "regionId": 710802 + }, + { + "name": "香山区", + "regionId": 710803 + }, + { + "name": "其它区", + "regionId": 710899 + } + ], + "name": "新竹市", + "regionId": 710800 + }, + { + "counties": [ + { + "name": "东区", + "regionId": 710901 + }, + { + "name": "西区", + "regionId": 710902 + }, + { + "name": "其它区", + "regionId": 710999 + } + ], + "name": "嘉义市", + "regionId": 710900 + }, + { + "counties": [ + { + "name": "万里区", + "regionId": 711130 + }, + { + "name": "板桥区", + "regionId": 711132 + }, + { + "name": "汐止区", + "regionId": 711133 + }, + { + "name": "深坑区", + "regionId": 711134 + }, + { + "name": "石碇区", + "regionId": 711135 + }, + { + "name": "瑞芳区", + "regionId": 711136 + }, + { + "name": "平溪区", + "regionId": 711137 + }, + { + "name": "双溪区", + "regionId": 711138 + }, + { + "name": "贡寮区", + "regionId": 711139 + }, + { + "name": "新店区", + "regionId": 711140 + }, + { + "name": "坪林区", + "regionId": 711141 + }, + { + "name": "乌来区", + "regionId": 711142 + }, + { + "name": "永和区", + "regionId": 711143 + }, + { + "name": "中和区", + "regionId": 711144 + }, + { + "name": "土城区", + "regionId": 711145 + }, + { + "name": "三峡区", + "regionId": 711146 + }, + { + "name": "树林区", + "regionId": 711147 + }, + { + "name": "莺歌区", + "regionId": 711148 + }, + { + "name": "三重区", + "regionId": 711149 + }, + { + "name": "新庄区", + "regionId": 711150 + }, + { + "name": "泰山区", + "regionId": 711151 + }, + { + "name": "林口区", + "regionId": 711152 + }, + { + "name": "芦洲区", + "regionId": 711153 + }, + { + "name": "五股区", + "regionId": 711154 + }, + { + "name": "八里区", + "regionId": 711155 + }, + { + "name": "淡水区", + "regionId": 711156 + }, + { + "name": "三芝区", + "regionId": 711157 + }, + { + "name": "石门区", + "regionId": 711158 + } + ], + "name": "新北市", + "regionId": 711100 + }, + { + "counties": [ + { + "name": "宜兰市", + "regionId": 711287 + }, + { + "name": "头城镇", + "regionId": 711288 + }, + { + "name": "礁溪乡", + "regionId": 711289 + }, + { + "name": "壮围乡", + "regionId": 711290 + }, + { + "name": "员山乡", + "regionId": 711291 + }, + { + "name": "罗东镇", + "regionId": 711292 + }, + { + "name": "三星乡", + "regionId": 711293 + }, + { + "name": "大同乡", + "regionId": 711294 + }, + { + "name": "五结乡", + "regionId": 711295 + }, + { + "name": "冬山乡", + "regionId": 711296 + }, + { + "name": "苏澳镇", + "regionId": 711297 + }, + { + "name": "南澳乡", + "regionId": 711298 + }, + { + "name": "钓鱼台", + "regionId": 711299 + } + ], + "name": "宜兰县", + "regionId": 711200 + }, + { + "counties": [ + { + "name": "竹北市", + "regionId": 711387 + }, + { + "name": "湖口乡", + "regionId": 711388 + }, + { + "name": "新丰乡", + "regionId": 711389 + }, + { + "name": "新埔镇", + "regionId": 711390 + }, + { + "name": "关西镇", + "regionId": 711391 + }, + { + "name": "芎林乡", + "regionId": 711392 + }, + { + "name": "宝山乡", + "regionId": 711393 + }, + { + "name": "竹东镇", + "regionId": 711394 + }, + { + "name": "五峰乡", + "regionId": 711395 + }, + { + "name": "横山乡", + "regionId": 711396 + }, + { + "name": "尖石乡", + "regionId": 711397 + }, + { + "name": "北埔乡", + "regionId": 711398 + }, + { + "name": "峨眉乡", + "regionId": 711399 + } + ], + "name": "新竹县", + "regionId": 711300 + }, + { + "counties": [ + { + "name": "中坜区", + "regionId": 711414 + }, + { + "name": "平镇区", + "regionId": 711415 + }, + { + "name": "杨梅区", + "regionId": 711417 + }, + { + "name": "新屋区", + "regionId": 711418 + }, + { + "name": "观音区", + "regionId": 711419 + }, + { + "name": "桃园区", + "regionId": 711420 + }, + { + "name": "龟山区", + "regionId": 711421 + }, + { + "name": "八德区", + "regionId": 711422 + }, + { + "name": "大溪区", + "regionId": 711423 + }, + { + "name": "大园区", + "regionId": 711425 + }, + { + "name": "芦竹区", + "regionId": 711426 + }, + { + "name": "中坜市", + "regionId": 711487 + }, + { + "name": "平镇市", + "regionId": 711488 + }, + { + "name": "龙潭乡", + "regionId": 711489 + }, + { + "name": "杨梅市", + "regionId": 711490 + }, + { + "name": "新屋乡", + "regionId": 711491 + }, + { + "name": "观音乡", + "regionId": 711492 + }, + { + "name": "桃园市", + "regionId": 711493 + }, + { + "name": "龟山乡", + "regionId": 711494 + }, + { + "name": "八德市", + "regionId": 711495 + }, + { + "name": "大溪镇", + "regionId": 711496 + }, + { + "name": "复兴乡", + "regionId": 711497 + }, + { + "name": "大园乡", + "regionId": 711498 + }, + { + "name": "芦竹乡", + "regionId": 711499 + } + ], + "name": "桃园县", + "regionId": 711400 + }, + { + "counties": [ + { + "name": "头份市", + "regionId": 711520 + }, + { + "name": "竹南镇", + "regionId": 711582 + }, + { + "name": "头份镇", + "regionId": 711583 + }, + { + "name": "三湾乡", + "regionId": 711584 + }, + { + "name": "南庄乡", + "regionId": 711585 + }, + { + "name": "狮潭乡", + "regionId": 711586 + }, + { + "name": "后龙镇", + "regionId": 711587 + }, + { + "name": "通霄镇", + "regionId": 711588 + }, + { + "name": "苑里镇", + "regionId": 711589 + }, + { + "name": "苗栗市", + "regionId": 711590 + }, + { + "name": "造桥乡", + "regionId": 711591 + }, + { + "name": "头屋乡", + "regionId": 711592 + }, + { + "name": "公馆乡", + "regionId": 711593 + }, + { + "name": "大湖乡", + "regionId": 711594 + }, + { + "name": "泰安乡", + "regionId": 711595 + }, + { + "name": "铜锣乡", + "regionId": 711596 + }, + { + "name": "三义乡", + "regionId": 711597 + }, + { + "name": "西湖乡", + "regionId": 711598 + }, + { + "name": "卓兰镇", + "regionId": 711599 + } + ], + "name": "苗栗县", + "regionId": 711500 + }, + { + "counties": [ + { + "name": "员林市", + "regionId": 711736 + }, + { + "name": "彰化市", + "regionId": 711774 + }, + { + "name": "芬园乡", + "regionId": 711775 + }, + { + "name": "花坛乡", + "regionId": 711776 + }, + { + "name": "秀水乡", + "regionId": 711777 + }, + { + "name": "鹿港镇", + "regionId": 711778 + }, + { + "name": "福兴乡", + "regionId": 711779 + }, + { + "name": "线西乡", + "regionId": 711780 + }, + { + "name": "和美镇", + "regionId": 711781 + }, + { + "name": "伸港乡", + "regionId": 711782 + }, + { + "name": "员林镇", + "regionId": 711783 + }, + { + "name": "社头乡", + "regionId": 711784 + }, + { + "name": "永靖乡", + "regionId": 711785 + }, + { + "name": "埔心乡", + "regionId": 711786 + }, + { + "name": "溪湖镇", + "regionId": 711787 + }, + { + "name": "大村乡", + "regionId": 711788 + }, + { + "name": "埔盐乡", + "regionId": 711789 + }, + { + "name": "田中镇", + "regionId": 711790 + }, + { + "name": "北斗镇", + "regionId": 711791 + }, + { + "name": "田尾乡", + "regionId": 711792 + }, + { + "name": "埤头乡", + "regionId": 711793 + }, + { + "name": "溪州乡", + "regionId": 711794 + }, + { + "name": "竹塘乡", + "regionId": 711795 + }, + { + "name": "二林镇", + "regionId": 711796 + }, + { + "name": "大城乡", + "regionId": 711797 + }, + { + "name": "芳苑乡", + "regionId": 711798 + }, + { + "name": "二水乡", + "regionId": 711799 + } + ], + "name": "彰化县", + "regionId": 711700 + }, + { + "counties": [ + { + "name": "番路乡", + "regionId": 711982 + }, + { + "name": "梅山乡", + "regionId": 711983 + }, + { + "name": "竹崎乡", + "regionId": 711984 + }, + { + "name": "阿里山乡", + "regionId": 711985 + }, + { + "name": "中埔乡", + "regionId": 711986 + }, + { + "name": "大埔乡", + "regionId": 711987 + }, + { + "name": "水上乡", + "regionId": 711988 + }, + { + "name": "鹿草乡", + "regionId": 711989 + }, + { + "name": "太保市", + "regionId": 711990 + }, + { + "name": "朴子市", + "regionId": 711991 + }, + { + "name": "东石乡", + "regionId": 711992 + }, + { + "name": "六脚乡", + "regionId": 711993 + }, + { + "name": "新港乡", + "regionId": 711994 + }, + { + "name": "民雄乡", + "regionId": 711995 + }, + { + "name": "大林镇", + "regionId": 711996 + }, + { + "name": "溪口乡", + "regionId": 711997 + }, + { + "name": "义竹乡", + "regionId": 711998 + }, + { + "name": "布袋镇", + "regionId": 711999 + } + ], + "name": "嘉义县", + "regionId": 711900 + }, + { + "counties": [ + { + "name": "斗南镇", + "regionId": 712180 + }, + { + "name": "大埤乡", + "regionId": 712181 + }, + { + "name": "虎尾镇", + "regionId": 712182 + }, + { + "name": "土库镇", + "regionId": 712183 + }, + { + "name": "褒忠乡", + "regionId": 712184 + }, + { + "name": "东势乡", + "regionId": 712185 + }, + { + "name": "台西乡", + "regionId": 712186 + }, + { + "name": "仑背乡", + "regionId": 712187 + }, + { + "name": "麦寮乡", + "regionId": 712188 + }, + { + "name": "斗六市", + "regionId": 712189 + }, + { + "name": "林内乡", + "regionId": 712190 + }, + { + "name": "古坑乡", + "regionId": 712191 + }, + { + "name": "莿桐乡", + "regionId": 712192 + }, + { + "name": "西螺镇", + "regionId": 712193 + }, + { + "name": "二仑乡", + "regionId": 712194 + }, + { + "name": "北港镇", + "regionId": 712195 + }, + { + "name": "水林乡", + "regionId": 712196 + }, + { + "name": "口湖乡", + "regionId": 712197 + }, + { + "name": "四湖乡", + "regionId": 712198 + }, + { + "name": "元长乡", + "regionId": 712199 + } + ], + "name": "云林县", + "regionId": 712100 + }, + { + "counties": [ + { + "name": "崁顶乡", + "regionId": 712451 + }, + { + "name": "屏东市", + "regionId": 712467 + }, + { + "name": "三地门乡", + "regionId": 712468 + }, + { + "name": "雾台乡", + "regionId": 712469 + }, + { + "name": "玛家乡", + "regionId": 712470 + }, + { + "name": "九如乡", + "regionId": 712471 + }, + { + "name": "里港乡", + "regionId": 712472 + }, + { + "name": "高树乡", + "regionId": 712473 + }, + { + "name": "盐埔乡", + "regionId": 712474 + }, + { + "name": "长治乡", + "regionId": 712475 + }, + { + "name": "麟洛乡", + "regionId": 712476 + }, + { + "name": "竹田乡", + "regionId": 712477 + }, + { + "name": "内埔乡", + "regionId": 712478 + }, + { + "name": "万丹乡", + "regionId": 712479 + }, + { + "name": "潮州镇", + "regionId": 712480 + }, + { + "name": "泰武乡", + "regionId": 712481 + }, + { + "name": "来义乡", + "regionId": 712482 + }, + { + "name": "万峦乡", + "regionId": 712483 + }, + { + "name": "莰顶乡", + "regionId": 712484 + }, + { + "name": "新埤乡", + "regionId": 712485 + }, + { + "name": "南州乡", + "regionId": 712486 + }, + { + "name": "林边乡", + "regionId": 712487 + }, + { + "name": "东港镇", + "regionId": 712488 + }, + { + "name": "琉球乡", + "regionId": 712489 + }, + { + "name": "佳冬乡", + "regionId": 712490 + }, + { + "name": "新园乡", + "regionId": 712491 + }, + { + "name": "枋寮乡", + "regionId": 712492 + }, + { + "name": "枋山乡", + "regionId": 712493 + }, + { + "name": "春日乡", + "regionId": 712494 + }, + { + "name": "狮子乡", + "regionId": 712495 + }, + { + "name": "车城乡", + "regionId": 712496 + }, + { + "name": "牡丹乡", + "regionId": 712497 + }, + { + "name": "恒春镇", + "regionId": 712498 + }, + { + "name": "满州乡", + "regionId": 712499 + } + ], + "name": "屏东县", + "regionId": 712400 + }, + { + "counties": [ + { + "name": "台东市", + "regionId": 712584 + }, + { + "name": "绿岛乡", + "regionId": 712585 + }, + { + "name": "兰屿乡", + "regionId": 712586 + }, + { + "name": "延平乡", + "regionId": 712587 + }, + { + "name": "卑南乡", + "regionId": 712588 + }, + { + "name": "鹿野乡", + "regionId": 712589 + }, + { + "name": "关山镇", + "regionId": 712590 + }, + { + "name": "海端乡", + "regionId": 712591 + }, + { + "name": "池上乡", + "regionId": 712592 + }, + { + "name": "东河乡", + "regionId": 712593 + }, + { + "name": "成功镇", + "regionId": 712594 + }, + { + "name": "长滨乡", + "regionId": 712595 + }, + { + "name": "金峰乡", + "regionId": 712596 + }, + { + "name": "大武乡", + "regionId": 712597 + }, + { + "name": "达仁乡", + "regionId": 712598 + }, + { + "name": "太麻里乡", + "regionId": 712599 + } + ], + "name": "台东县", + "regionId": 712500 + }, + { + "counties": [ + { + "name": "花莲市", + "regionId": 712686 + }, + { + "name": "新城乡", + "regionId": 712687 + }, + { + "name": "太鲁阁", + "regionId": 712688 + }, + { + "name": "秀林乡", + "regionId": 712689 + }, + { + "name": "吉安乡", + "regionId": 712690 + }, + { + "name": "寿丰乡", + "regionId": 712691 + }, + { + "name": "凤林镇", + "regionId": 712692 + }, + { + "name": "光复乡", + "regionId": 712693 + }, + { + "name": "丰滨乡", + "regionId": 712694 + }, + { + "name": "瑞穗乡", + "regionId": 712695 + }, + { + "name": "万荣乡", + "regionId": 712696 + }, + { + "name": "玉里镇", + "regionId": 712697 + }, + { + "name": "卓溪乡", + "regionId": 712698 + }, + { + "name": "富里乡", + "regionId": 712699 + } + ], + "name": "花莲县", + "regionId": 712600 + }, + { + "counties": [ + { + "name": "马公市", + "regionId": 712794 + }, + { + "name": "西屿乡", + "regionId": 712795 + }, + { + "name": "望安乡", + "regionId": 712796 + }, + { + "name": "七美乡", + "regionId": 712797 + }, + { + "name": "白沙乡", + "regionId": 712798 + }, + { + "name": "湖西乡", + "regionId": 712799 + } + ], + "name": "澎湖县", + "regionId": 712700 + }, + { + "counties": [ + { + "name": "南竿乡", + "regionId": 712896 + }, + { + "name": "北竿乡", + "regionId": 712897 + }, + { + "name": "东引乡", + "regionId": 712898 + }, + { + "name": "莒光乡", + "regionId": 712899 + } + ], + "name": "连江县", + "regionId": 712800 + } + ], + "name": "台湾省", + "regionId": 710000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "中西区", + "regionId": 810101 + }, + { + "name": "湾仔区", + "regionId": 810102 + }, + { + "name": "东区", + "regionId": 810103 + }, + { + "name": "南区", + "regionId": 810104 + } + ], + "name": "香港岛", + "regionId": 810100 + }, + { + "counties": [ + { + "name": "九龙城区", + "regionId": 810201 + }, + { + "name": "油尖旺区", + "regionId": 810202 + }, + { + "name": "深水埗区", + "regionId": 810203 + }, + { + "name": "黄大仙区", + "regionId": 810204 + }, + { + "name": "观塘区", + "regionId": 810205 + } + ], + "name": "九龙", + "regionId": 810200 + }, + { + "counties": [ + { + "name": "北区", + "regionId": 810301 + }, + { + "name": "大埔区", + "regionId": 810302 + }, + { + "name": "沙田区", + "regionId": 810303 + }, + { + "name": "西贡区", + "regionId": 810304 + }, + { + "name": "元朗区", + "regionId": 810305 + }, + { + "name": "屯门区", + "regionId": 810306 + }, + { + "name": "荃湾区", + "regionId": 810307 + }, + { + "name": "葵青区", + "regionId": 810308 + }, + { + "name": "离岛区", + "regionId": 810309 + } + ], + "name": "新界", + "regionId": 810300 + } + ], + "name": "香港特别行政区", + "regionId": 810000 + }, + { + "cities": [ + { + "counties": [ + { + "name": "花地玛堂区", + "regionId": 820102 + }, + { + "name": "花王堂区", + "regionId": 820103 + }, + { + "name": "望德堂区", + "regionId": 820104 + }, + { + "name": "大堂区", + "regionId": 820105 + }, + { + "name": "风顺堂区", + "regionId": 820106 + } + ], + "name": "澳门半岛", + "regionId": 820100 + }, + { + "counties": [ + { + "name": "嘉模堂区", + "regionId": 820202 + }, + { + "name": "路氹填海区", + "regionId": 820203 + }, + { + "name": "圣方济各堂区", + "regionId": 820204 + } + ], + "name": "离岛", + "regionId": 820200 + } + ], + "name": "澳门特别行政区", + "regionId": 820000 + } + ] + } + ] +} diff --git a/internal/freight/region_index.go b/internal/freight/region_index.go new file mode 100644 index 0000000..e6b3b1b --- /dev/null +++ b/internal/freight/region_index.go @@ -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 + } +} diff --git a/internal/freight/rules_json.go b/internal/freight/rules_json.go new file mode 100644 index 0000000..1c269ee --- /dev/null +++ b/internal/freight/rules_json.go @@ -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 +} diff --git a/internal/freight/rules_json_test.go b/internal/freight/rules_json_test.go new file mode 100644 index 0000000..9aa02f7 --- /dev/null +++ b/internal/freight/rules_json_test.go @@ -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") + } +} diff --git a/internal/postgresutc/open.go b/internal/postgresutc/open.go new file mode 100644 index 0000000..b1cdfa1 --- /dev/null +++ b/internal/postgresutc/open.go @@ -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 +} diff --git a/internal/repository/catalog_master_repository.go b/internal/repository/catalog_master_repository.go new file mode 100644 index 0000000..f15a1e1 --- /dev/null +++ b/internal/repository/catalog_master_repository.go @@ -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 +} diff --git a/internal/repository/catalog_master_repository_test.go b/internal/repository/catalog_master_repository_test.go new file mode 100644 index 0000000..4349dcf --- /dev/null +++ b/internal/repository/catalog_master_repository_test.go @@ -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) + } +} diff --git a/internal/repository/category_binding_test.go b/internal/repository/category_binding_test.go new file mode 100644 index 0000000..bf97430 --- /dev/null +++ b/internal/repository/category_binding_test.go @@ -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) + } +} diff --git a/internal/repository/freight_template_repository.go b/internal/repository/freight_template_repository.go new file mode 100644 index 0000000..83d1635 --- /dev/null +++ b/internal/repository/freight_template_repository.go @@ -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 +} diff --git a/internal/repository/freight_template_repository_test.go b/internal/repository/freight_template_repository_test.go new file mode 100644 index 0000000..3a55072 --- /dev/null +++ b/internal/repository/freight_template_repository_test.go @@ -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) + } +} diff --git a/internal/repository/product_batch.go b/internal/repository/product_batch.go new file mode 100644 index 0000000..77d7afb --- /dev/null +++ b/internal/repository/product_batch.go @@ -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 +} diff --git a/internal/repository/product_batch_test.go b/internal/repository/product_batch_test.go new file mode 100644 index 0000000..8e25dc7 --- /dev/null +++ b/internal/repository/product_batch_test.go @@ -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") + } +} diff --git a/internal/repository/product_category_repository.go b/internal/repository/product_category_repository.go new file mode 100644 index 0000000..7e45c48 --- /dev/null +++ b/internal/repository/product_category_repository.go @@ -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 +} diff --git a/internal/repository/product_presale_migration.go b/internal/repository/product_presale_migration.go new file mode 100644 index 0000000..35e51bd --- /dev/null +++ b/internal/repository/product_presale_migration.go @@ -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) +} diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index 9051dd6..66f5b14 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -21,9 +21,24 @@ var ErrProductNotFound = errors.New("product not found") // ErrCategoryNodeNotFound is returned when a category or product group node does not exist. var ErrCategoryNodeNotFound = errors.New("category or group node not found") + +// ErrStorefrontCategoryNotFound deliberately also covers a hidden category or +// a category below a hidden/missing ancestor. Storefront callers must not be +// able to distinguish those states from a category that does not exist. +var ErrStorefrontCategoryNotFound = errors.New("storefront category not found") var ErrCategoryVersionConflict = errors.New("category version conflict") var ErrCategoryTreeConflict = errors.New("category tree conflict") -var ErrInvalidLeafCategory = errors.New("category must be an existing second-level category") +var ErrCategoryNameExists = errors.New("category name already exists") +var ErrGroupNameExists = errors.New("group name already exists") +var ErrInvalidLeafCategory = errors.New("category must be an existing terminal catalog category") + +// ErrInvalidProductGroup is returned when a requested node is not a group in +// the current store. +var ErrInvalidProductGroup = errors.New("group must be an existing product group") + +// ErrInvalidProductCategory is returned when a requested standard product +// category is missing, disabled, deleted, or not a terminal node. +var ErrInvalidProductCategory = errors.New("product category must be an enabled terminal product category") // ErrSKUNotFound is returned when a SKU does not exist. var ErrSKUNotFound = errors.New("sku not found") @@ -37,9 +52,14 @@ var ErrInsufficientLockedStock = errors.New("insufficient locked stock") // ErrInventoryAdjustmentConflict is returned when an idempotent inventory adjustment is replayed with different data. var ErrInventoryAdjustmentConflict = errors.New("inventory adjustment conflict") -// ErrProductNotOnSale is returned when a new inventory reservation targets a product that is not on sale. +// ErrProductNotOnSale is returned when a new inventory reservation targets a product in the warehouse state. var ErrProductNotOnSale = errors.New("product is not on sale") +// ErrProductSoldOut is returned when a new inventory reservation targets a +// product whose lifecycle status is SOLD_OUT (database value 3). A sold-out +// product may retain physical inventory, but it must not accept new locks. +var ErrProductSoldOut = errors.New("product is sold out") + // ErrDuplicateSPUNo is returned when a non-deleted product already uses the SPU number. var ErrDuplicateSPUNo = errors.New("spu_no already exists") @@ -55,33 +75,62 @@ var ErrSKUArchived = errors.New("sku is archived") // ErrSKUReplacementRequiresNotOnSale is returned when replacing SKUs for an on-sale product. var ErrSKUReplacementRequiresNotOnSale = errors.New("sku replacement requires inventory or off-sale product status") +// ErrSameStore is returned when a store transfer targets the product's current store. +var ErrSameStore = errors.New("target store is the current store") + // ProductRecord is the persistence model for product.products (SPU). type ProductRecord struct { - ID string - SPUNo string - Title string - SellingPoint string - BrandID string - SupplierID string - ImageIDs []string - DetailHTML string - MemberDiscountEnabled bool - GoodsType int32 - ServiceGuarantees []string - Status productv1.ProductStatus - Attrs map[string]any - CrossBorderJSON string - FreightChargeType int32 - FreightFixedAmount int64 - FreightTemplateID string - SaleTimeType int32 - ScheduledSaleTime *time.Time - LeafCategoryIDs []string - CategoryBindingIDs []string - Version int32 - DeletedAt *time.Time - CreatedAt time.Time - UpdatedAt time.Time + ID string + SPUNo string + Title string + SellingPoint string + BrandID string + SupplierID string + ImageIDs []string + DetailHTML string + MemberDiscountEnabled bool + IsDistributionProduct bool + DistributionProductDetailJSON string + GoodsType int32 + ServiceGuarantees []string + Status productv1.ProductStatus + Attrs map[string]any + CrossBorderJSON string + CategoryPropertiesJSON string + FreightChargeType int32 + FreightFixedAmount int64 + FreightTemplateID string + SaleTimeType int32 + ScheduledSaleTime *time.Time + PresaleType int32 + DeliveryTimeType int32 + DeliveryStartAt *time.Time + DeliveryAfterPaidDays int32 + PurchaseLimitQuantity int32 + LeafCategoryIDs []string + CategoryBindingIDs []string + GroupIDs []string + GroupBindingIDs []string + ProductCategoryIDs []string + ProductCategoryBindingIDs []string + ProductCategories []ProductCategorySummaryRecord + Version int32 + DeletedAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time + Scope StoreScope +} + +// ProductFreightChargeUpdate is the persisted freight projection returned by +// the dedicated freight-charge update command. +type ProductFreightChargeUpdate struct { + ProductID string + SPUNo string + FreightChargeType int32 + FreightFixedAmount int64 + FreightTemplateID string + Version int32 + UpdatedAt time.Time } // ProductCountRecord contains aggregate counts for product.products. @@ -101,6 +150,9 @@ type SKURecord struct { SKUNo string Name string Price int64 + SupplyPrice *int64 + WeightKg *float64 + Barcode string ImageIDs []string StockQuantity int32 LockedQuantity int32 @@ -122,6 +174,14 @@ type SKURecord struct { Inventory *InventoryRecord } +// ProductSKUStockRecord is the compact current-SKU projection used by SKU list queries. +type ProductSKUStockRecord struct { + ID string + Name string + StockQuantity int32 + SupplyPrice *int64 +} + // InventoryRecord is the persistence model for product.product_item_inventory. type InventoryRecord struct { ID string @@ -156,6 +216,14 @@ type CartItemProductRecord struct { SKU *SKURecord } +// StorefrontProductSKURecord is the minimal current-SKU projection used when +// a storefront needs to evaluate display-only promotions for product cards. +type StorefrontProductSKURecord struct { + ProductID string + SKUID string + Price int64 +} + // SKUChangeMode selects how SKU input is applied during a product update. type SKUChangeMode int32 @@ -171,6 +239,11 @@ type SKUUpdate struct { ExpectedInventoryVersion int32 Name *string Price *int64 + SupplyPrice *int64 + SupplyPriceSet bool + WeightKg *float64 + WeightKgSet bool + Barcode *string StockQuantity *int32 Status *int32 ImageIDs *[]string @@ -192,6 +265,15 @@ type ProductUpdateInput struct { // non-nil empty slice clears all leaf-category bindings. LeafCategoryIDs *[]string CategoryBindingIDs []string + // GroupIDs is nil when group bindings must remain unchanged. A non-nil + // empty slice clears all product-group bindings. + GroupIDs *[]string + GroupBindingIDs []string + // ProductCategoryIDs is nil when standard product-category bindings must + // remain unchanged. A non-nil empty slice clears all such bindings. + ProductCategoryIDs *[]string + ProductCategoryBindingIDs []string + Scope StoreScope } // CategoryDeleteResult summarizes a destructive category deletion. @@ -222,30 +304,178 @@ type ProductStatusUpdate struct { // CategoryProductRecord is the product summary returned by product list endpoints. type CategoryProductRecord struct { - ID string - SPUNo string - Title string - Status productv1.ProductStatus - ImageIDs []string - Price int64 - SoldQuantity int64 - StockQuantity int64 - LockedQuantity int64 - CreatedAt time.Time - UpdatedAt time.Time + ID string + SPUNo string + Title string + Status productv1.ProductStatus + ImageIDs []string + Price int64 + SoldQuantity int64 + StockQuantity int64 + LockedQuantity int64 + CategoryPropertiesJSON string + IsDistributionProduct bool + PresaleType int32 + ProductCategories []ProductCategorySummaryRecord + Groups []ProductGroupSummaryRecord + Brand *ProductBrandSummaryRecord + CreatedAt time.Time + UpdatedAt time.Time } -// CategoryRecord is the persistence model for product.product_category. -type CategoryRecord struct { +// ProductCategoryPathNodeRecord is one root-to-leaf node in a standard +// product-category path. +type ProductCategoryPathNodeRecord struct { ID string - NodeType int32 Name string - ParentID string Level int32 - ImageIDs []string - SortNum int32 - Status int32 - Version int32 + ParentID *string +} + +// ProductCategorySummaryRecord describes one standard category directly bound +// to a product, along with its immediate parent and complete ancestor path. +type ProductCategorySummaryRecord struct { + ID string + Name string + Level int32 + ParentID *string + ParentName string + Path []ProductCategoryPathNodeRecord +} + +// ProductGroupSummaryRecord describes one product-group binding. +type ProductGroupSummaryRecord struct { + ID string + Name string +} + +// ProductBrandSummaryRecord is the display projection of a product brand. +type ProductBrandSummaryRecord struct { + ID string + Name string + Alias string + BrandCode string +} + +// ProductListFilter contains the optional constraints for an admin product list. +type ProductListFilter struct { + CreatedAtFrom *time.Time + CreatedAtTo *time.Time + TitleKeyword string + SPUNo string + GroupID string + // ProductCategoryID identifies the standard business taxonomy stored in + // product.product_category. It is intentionally separate from storefront + // catalog categories and product groups. + ProductCategoryID string + GoodsType *int32 + SoldQuantityMin *int64 + SoldQuantityMax *int64 + PriceMin *int64 + PriceMax *int64 + PresaleType *int32 + Status *productv1.ProductStatus +} + +// CategoryRecord is the persistence model for product.catalog_category. +type CategoryRecord struct { + ID string + NodeType int32 + Name string + ParentID string + Level int32 + ImageIDs []string + SortNum int32 + Status int32 + CampaignID string + Version int32 + // ProductCount is populated when listing product groups. + ProductCount int64 + // IsLeaf and BrandProducts are populated when listing product groups. + IsLeaf bool + BrandProducts []GroupBrandProductRecord + // Children is populated for catalog-category tree operations. + Children []CategoryRecord +} + +// GroupBrandProductRecord is one leaf group's direct product bindings for a brand. +type GroupBrandProductRecord struct { + BrandID string + BrandName string + Products []GroupBrandProductItemRecord +} + +// GroupBrandProductItemRecord is one product and its SPU number in a brand group. +type GroupBrandProductItemRecord struct { + ProductID string + SPUNo string +} + +// CreateCatalogCategoryTree inserts a catalog-category subtree of arbitrary +// depth. The request root may be attached to an existing catalog category. +func (r *ProductRepository) CreateCatalogCategoryTree(ctx context.Context, root CategoryRecord, children []CategoryRecord, scope StoreScope) (*CategoryRecord, []*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, nil, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, nil, fmt.Errorf("begin create catalog category tree: %w", err) + } + defer tx.Rollback() + root.Children = children + created, err := r.createCatalogCategoryNode(ctx, tx, root, root.ParentID, scope) + if err != nil { + return nil, nil, err + } + if err := tx.Commit(); err != nil { + return nil, nil, fmt.Errorf("commit create catalog category tree: %w", err) + } + return created, categoryRecordPointers(created.Children), nil +} + +func categoryRecordPointers(values []CategoryRecord) []*CategoryRecord { + result := make([]*CategoryRecord, 0, len(values)) + for index := range values { + result = append(result, &values[index]) + } + return result +} + +func (r *ProductRepository) createCatalogCategoryNode(ctx context.Context, tx *sql.Tx, input CategoryRecord, parentID string, scope StoreScope) (*CategoryRecord, error) { + input.NodeType = 1 + input.ParentID = strings.TrimSpace(parentID) + if input.ParentID == "" { + input.Level = 1 + } else { + parent, err := loadCategoryForUpdate(ctx, tx, input.ParentID, scope) + if err != nil { + return nil, err + } + if parent.NodeType != 1 { + return nil, ErrCategoryTreeConflict + } + input.Level = parent.Level + 1 + } + created, err := insertCategoryNode(ctx, tx, input, scope) + if err != nil { + return nil, err + } + for _, child := range input.Children { + value, err := r.createCatalogCategoryNode(ctx, tx, child, created.ID, scope) + if err != nil { + return nil, err + } + created.Children = append(created.Children, *value) + } + return created, nil +} + +// GroupListFilter contains optional product-group list constraints. +type GroupListFilter struct { + OnlyVisible bool + FirstLevelName string + SecondLevelName string + ExactMatch bool } // CategoryFieldUpdate selects mutable fields of one category node. @@ -256,6 +486,7 @@ type CategoryFieldUpdate struct { ImageIDs *[]string SortNum *int32 Status *int32 + CampaignID *string } // CategoryTreeUpdate groups an optional root update with direct-child updates. @@ -279,16 +510,56 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` +DO $$ +BEGIN + IF to_regclass('product.catalog_category') IS NULL + AND to_regclass('product.product_category') IS NOT NULL THEN + ALTER TABLE product.product_category RENAME TO catalog_category; + END IF; + IF to_regclass('product.product_catalog_bindings') IS NULL + AND to_regclass('product.product_category_bindings') IS NOT NULL THEN + ALTER TABLE product.product_category_bindings RENAME TO product_catalog_bindings; + END IF; +END $$; + ALTER TABLE product.products ALTER COLUMN id DROP DEFAULT; -ALTER TABLE product.product_category_bindings +ALTER TABLE product.product_catalog_bindings ALTER COLUMN id DROP DEFAULT; -ALTER TABLE product.product_category +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; + +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; -ALTER TABLE product.product_category +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0; DO $$ @@ -298,7 +569,7 @@ BEGIN WHERE conname = 'chk_product_category_version' AND connamespace = 'product'::regnamespace ) THEN - ALTER TABLE product.product_category + ALTER TABLE product.catalog_category ADD CONSTRAINT chk_product_category_version CHECK (version >= 0); END IF; END $$; @@ -309,11 +580,11 @@ BEGIN SELECT 1 FROM information_schema.columns WHERE table_schema = 'product' - AND table_name = 'product_category' + AND table_name = 'catalog_category' AND column_name = 'image_json' ) THEN EXECUTE $migration$ - UPDATE product.product_category + UPDATE product.catalog_category SET image_ids = CASE WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE( (SELECT array_agg(image_id) @@ -327,15 +598,78 @@ BEGIN END IF; END $$; -ALTER TABLE product.product_category +ALTER TABLE product.catalog_category DROP COLUMN IF EXISTS image_json; +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 +); + +-- CREATE TABLE IF NOT EXISTS does not alter a table created by an earlier +-- service version. Add columns required by indexes / newer code before use. +ALTER TABLE product.product_category + ADD COLUMN IF NOT EXISTS priority INTEGER NOT NULL DEFAULT 0; +-- Taxonomy is rebuilt before this version is deployed, so these mandatory +-- source columns can be added without a legacy backfill. +ALTER TABLE product.product_category + ADD COLUMN IF NOT EXISTS platform_category_id BIGINT NOT NULL CHECK (platform_category_id > 0), + ADD COLUMN IF NOT EXISTS platform_parent_category_id BIGINT NOT NULL CHECK (platform_parent_category_id >= 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 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 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 + ON product.product_category_bindings (store_id, product_category_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 '{}', status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)), @@ -374,18 +708,125 @@ ALTER TABLE product.product_items ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; +ALTER TABLE product.product_items + ADD COLUMN IF NOT EXISTS supply_price BIGINT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS is_archived BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ; CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL AND is_archived = FALSE; CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items(price) WHERE deleted_at IS NULL AND is_archived = FALSE; -CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE; CREATE INDEX IF NOT EXISTS idx_products_active_created_id ON product.products(created_at DESC, id DESC) WHERE deleted_at IS NULL; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS tenant_id BIGINT; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS store_id BIGINT; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS is_distribution_product BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS distribution_product_detail JSONB NOT NULL DEFAULT '{}'::JSONB; +ALTER TABLE product.products ADD COLUMN IF NOT EXISTS category_properties JSONB NOT NULL DEFAULT '{}'::JSONB; +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) + ) +); +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS tenant_id BIGINT; +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS store_id BIGINT; +ALTER TABLE product.catalog_category ADD COLUMN IF NOT EXISTS campaign_id BIGINT; +ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS tenant_id BIGINT; +ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS store_id BIGINT; +ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS weight_kg DOUBLE PRECISION; +ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS barcode VARCHAR(64); +DROP INDEX IF EXISTS product.uq_products_spu_no; +DROP INDEX IF EXISTS product.uq_products_store_spu_no; +CREATE UNIQUE INDEX IF NOT EXISTS uq_products_store_spu_no + ON product.products (store_id, spu_no) + WHERE deleted_at IS NULL AND spu_no <> ''; +CREATE INDEX IF NOT EXISTS idx_products_store_id ON product.products (store_id) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_products_store_presale_created_id + ON product.products (store_id, presale_type, created_at DESC, id DESC) WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_catalog_category_store_id ON product.catalog_category (store_id); +CREATE INDEX IF NOT EXISTS idx_catalog_category_store_type_parent_status_sort + ON product.catalog_category (store_id, node_type, parent_id, status, sort_num, id) + WHERE deleted_at IS NULL; +COMMENT ON COLUMN product.catalog_category.level IS + 'Server-maintained hierarchy level: root is 1 and each child is parent level plus 1.'; +CREATE INDEX IF NOT EXISTS idx_product_category_campaign_id + ON product.catalog_category (campaign_id) WHERE campaign_id IS NOT NULL AND 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; +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; +DROP INDEX IF EXISTS product.uq_product_items_sku_no; +DROP INDEX IF EXISTS product.uq_product_items_sku_no_active; +DROP INDEX IF EXISTS product.uq_product_items_store_sku_no_active; +CREATE INDEX IF NOT EXISTS idx_product_items_store_id ON product.product_items (store_id) WHERE deleted_at IS NULL; +CREATE TABLE IF NOT EXISTS product.suppliers ( + 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; ` if _, err := r.db.ExecContext(ctx, ddl); err != nil { return fmt.Errorf("ensure product tables: %w", err) } + if err := r.ensureFreightTemplateSchema(ctx); err != nil { + return fmt.Errorf("ensure freight template schema: %w", err) + } return nil } @@ -395,6 +836,10 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe if err != nil { return err } + categoryProperties, err := productCategoryPropertiesJSON(product) + if err != nil { + return err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { @@ -402,7 +847,7 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe } defer tx.Rollback() - if _, err := insertProduct(ctx, tx, product, attrs); err != nil { + if _, err := insertProduct(ctx, tx, product, attrs, categoryProperties); err != nil { return err } if err := tx.Commit(); err != nil { @@ -413,10 +858,17 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe // CreateProductWithSKUs inserts an SPU and its optional SKU list in one transaction. func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product ProductRecord, skus []SKURecord) (*ProductRecord, []SKURecord, error) { + if err := requireWriteScope(product.Scope); err != nil { + return nil, nil, err + } attrs, err := productCrossBorderJSON(product) if err != nil { return nil, nil, err } + categoryProperties, err := productCategoryPropertiesJSON(product) + if err != nil { + return nil, nil, err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { @@ -424,7 +876,7 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } defer tx.Rollback() - createdProduct, err := insertProduct(ctx, tx, product, attrs) + createdProduct, err := insertProduct(ctx, tx, product, attrs, categoryProperties) if err != nil { return nil, nil, err } @@ -439,7 +891,17 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } if len(product.LeafCategoryIDs) > 0 { - if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs); err != nil { + if err := replaceProductLeafCategoryBindings(ctx, tx, createdProduct.ID, product.LeafCategoryIDs, product.CategoryBindingIDs, product.Scope); err != nil { + return nil, nil, err + } + } + if len(product.GroupIDs) > 0 { + if err := replaceProductGroupBindings(ctx, tx, createdProduct.ID, product.GroupIDs, product.GroupBindingIDs, product.Scope); err != nil { + return nil, nil, err + } + } + if len(product.ProductCategoryIDs) > 0 { + if err := replaceProductStandardCategoryBindings(ctx, tx, createdProduct.ID, product.ProductCategoryIDs, product.ProductCategoryBindingIDs, product.Scope); err != nil { return nil, nil, err } } @@ -452,14 +914,17 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } // CreateCategoryTree inserts a top-level category and its optional child categories in one transaction. -func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent CategoryRecord, children []CategoryRecord) (*CategoryRecord, []*CategoryRecord, error) { +func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent CategoryRecord, children []CategoryRecord, scope StoreScope) (*CategoryRecord, []*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, nil, err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { return nil, nil, fmt.Errorf("begin create category tree: %w", err) } defer tx.Rollback() - createdParent, err := insertCategoryNode(ctx, tx, parent) + createdParent, err := insertCategoryNode(ctx, tx, parent, scope) if err != nil { return nil, nil, err } @@ -470,7 +935,7 @@ func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent Categ child.ParentID = createdParent.ID child.Level = createdParent.Level + 1 - createdChild, err := insertCategoryNode(ctx, tx, child) + createdChild, err := insertCategoryNode(ctx, tx, child, scope) if err != nil { return nil, nil, err } @@ -485,14 +950,17 @@ func (r *ProductRepository) CreateCategoryTree(ctx context.Context, parent Categ } // CreateCategoryNode inserts a single product category/group node. -func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category CategoryRecord) (*CategoryRecord, error) { +func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category CategoryRecord, scope StoreScope) (*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { return nil, fmt.Errorf("begin create category node: %w", err) } defer tx.Rollback() - createdCategory, err := insertCategoryNode(ctx, tx, category) + createdCategory, err := insertCategoryNode(ctx, tx, category, scope) if err != nil { return nil, err } @@ -502,9 +970,88 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat return createdCategory, nil } +// CreateGroupNode inserts a first-level group or a child of a first-level group. +func (r *ProductRepository) CreateGroupNode(ctx context.Context, group CategoryRecord, scope StoreScope) (*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin create group node: %w", err) + } + defer tx.Rollback() + + group.NodeType = 2 + if group.ParentID == "" { + group.Level = 1 + } else { + parent, err := loadCategoryForUpdate(ctx, tx, group.ParentID, scope) + if errors.Is(err, ErrCategoryNodeNotFound) { + return nil, ErrInvalidProductGroup + } + if err != nil { + return nil, err + } + if parent.NodeType != 2 || parent.Level != 1 || parent.ParentID != "" { + return nil, ErrInvalidProductGroup + } + group.ParentID = parent.ID + group.Level = 2 + } + createdGroup, err := insertCategoryNode(ctx, tx, group, scope) + if err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit create group node: %w", err) + } + return createdGroup, nil +} + +// CreateGroupChildren inserts a batch of second-level groups under one locked first-level group. +func (r *ProductRepository) CreateGroupChildren(ctx context.Context, parentID string, children []CategoryRecord, scope StoreScope) ([]*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if len(children) == 0 { + return nil, errors.New("children is required") + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin create group children: %w", err) + } + defer tx.Rollback() + + parent, err := loadCategoryForUpdate(ctx, tx, parentID, scope) + if err != nil { + return nil, err + } + if parent.NodeType != 2 || parent.Level != 1 || parent.ParentID != "" { + return nil, ErrInvalidProductGroup + } + created := make([]*CategoryRecord, 0, len(children)) + for _, child := range children { + child.NodeType = 2 + child.ParentID = parent.ID + child.Level = 2 + node, err := insertCategoryNode(ctx, tx, child, scope) + if err != nil { + return nil, err + } + created = append(created, node) + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit create group children: %w", err) + } + return created, nil +} + // UpdateCategoryTrees applies all requested root and direct-child patches in a // single transaction. Callers must supply already-validated patch fields. -func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate) error { +func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } if len(updates) == 0 { return errors.New("category_trees is required") } @@ -515,7 +1062,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C defer tx.Rollback() for _, tree := range updates { - root, err := loadCategoryForUpdate(ctx, tx, tree.CategoryID) + root, err := loadCategoryForUpdate(ctx, tx, tree.CategoryID, scope) if err != nil { return err } @@ -531,7 +1078,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C } } for _, child := range tree.Children { - current, err := loadCategoryForUpdate(ctx, tx, child.ID) + current, err := loadCategoryForUpdate(ctx, tx, child.ID, scope) if err != nil { return err } @@ -546,7 +1093,7 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C child.NodeType = 1 child.ParentID = tree.CategoryID child.Level = 2 - if _, err := insertCategoryNode(ctx, tx, child); err != nil { + if _, err := insertCategoryNode(ctx, tx, child, scope); err != nil { return err } } @@ -560,7 +1107,10 @@ func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []C // DeleteCategory removes a leaf category or a complete top-level category tree // and all affected product bindings in one transaction. Product rows and group // bindings are deliberately retained. -func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32) (*CategoryDeleteResult, error) { +func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID string, expectedVersion int32, scope StoreScope) (*CategoryDeleteResult, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } if expectedVersion < 0 { return nil, errors.New("expected_version must be non-negative") } @@ -570,59 +1120,50 @@ func (r *ProductRepository) DeleteCategory(ctx context.Context, categoryID strin } defer tx.Rollback() - target, err := loadCategoryForUpdate(ctx, tx, categoryID) + target, err := loadCategoryForUpdate(ctx, tx, categoryID, scope) if err != nil { return nil, err } - if target.NodeType != 1 || (target.Level != 1 && target.Level != 2) { + if target.NodeType != 1 { return nil, ErrCategoryTreeConflict } if target.Version != expectedVersion { return nil, ErrCategoryVersionConflict } - categoryIDs := []int64{} targetID, err := parseID(target.ID, "category_id") if err != nil { return nil, err } - if target.Level == 1 { - rows, err := tx.QueryContext(ctx, ` -SELECT id, node_type, name, parent_id, level, - COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version -FROM product.product_category -WHERE parent_id = $1 -FOR UPDATE -`, targetID) - if err != nil { - return nil, fmt.Errorf("load category children for delete: %w", err) - } - for rows.Next() { - child, err := scanCategory(rows) - if err != nil { - rows.Close() - return nil, err - } - if child.NodeType != 1 || child.Level != 2 || child.ParentID != target.ID { - rows.Close() - return nil, ErrCategoryTreeConflict - } - childID, err := parseID(child.ID, "category_id") - if err != nil { - rows.Close() - return nil, err - } - categoryIDs = append(categoryIDs, childID) - } - if err := rows.Err(); err != nil { - rows.Close() - return nil, fmt.Errorf("iterate category children for delete: %w", err) - } - if err := rows.Close(); err != nil { - return nil, fmt.Errorf("close category children for delete: %w", err) - } + rows, err := tx.QueryContext(ctx, ` +WITH RECURSIVE descendants(id, path) AS ( + SELECT id, ARRAY[id] FROM product.catalog_category WHERE id = $1 AND store_id = $2 AND node_type = 1 AND deleted_at IS NULL + UNION ALL + SELECT child.id, parent.path || child.id + FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id + WHERE child.store_id = $2 AND child.node_type = 1 AND child.deleted_at IS NULL AND NOT child.id = ANY(parent.path) +) +SELECT id FROM descendants +`, targetID, scope.StoreID) + if err != nil { + return nil, fmt.Errorf("load category descendants for delete: %w", err) + } + categoryIDs := make([]int64, 0) + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + rows.Close() + return nil, err + } + categoryIDs = append(categoryIDs, id) + } + if err := rows.Err(); err != nil { + rows.Close() + return nil, fmt.Errorf("iterate category descendants for delete: %w", err) + } + if err := rows.Close(); err != nil { + return nil, fmt.Errorf("close category descendants for delete: %w", err) } - categoryIDs = append(categoryIDs, targetID) placeholders := make([]string, len(categoryIDs)) args := make([]any, len(categoryIDs)) for index, id := range categoryIDs { @@ -638,24 +1179,20 @@ FOR UPDATE } if err := tx.QueryRowContext(ctx, fmt.Sprintf(` SELECT COUNT(DISTINCT product_id), COUNT(*) -FROM product.product_category_bindings -WHERE category_id IN (%s) +FROM product.product_catalog_bindings +WHERE category_id IN (%s) AND deleted_at IS NULL `, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil { return nil, fmt.Errorf("count category bindings for delete: %w", err) } if _, err := tx.ExecContext(ctx, fmt.Sprintf(` -DELETE FROM product.product_category_bindings -WHERE category_id IN (%s) +UPDATE product.product_catalog_bindings +SET deleted_at = NOW(), updated_at = NOW() +WHERE category_id IN (%s) AND deleted_at IS NULL `, whereIDs), args...); err != nil { return nil, fmt.Errorf("delete category bindings: %w", err) } - if target.Level == 1 { - if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE parent_id = $1`, targetID); err != nil { - return nil, fmt.Errorf("delete child categories: %w", err) - } - } - if _, err := tx.ExecContext(ctx, `DELETE FROM product.product_category WHERE id = $1`, targetID); err != nil { - return nil, fmt.Errorf("delete category: %w", err) + if _, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE product.catalog_category SET deleted_at = NOW(), updated_at = NOW(), version = version + 1 WHERE id IN (%s) AND store_id = $%d AND deleted_at IS NULL`, whereIDs, len(args)+1), append(args, scope.StoreID)...); err != nil { + return nil, fmt.Errorf("delete category tree: %w", err) } if err := tx.Commit(); err != nil { return nil, fmt.Errorf("commit delete category: %w", err) @@ -663,17 +1200,170 @@ WHERE category_id IN (%s) return result, nil } -func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string) (*CategoryRecord, error) { +// GroupDeleteResult summarizes a soft-deleted product-group deletion. +type GroupDeleteResult struct { + DeletedGroupID string + UnboundProductCount int64 + UnboundBindingCount int64 +} + +// UpdateGroup applies a field patch to one product group (node_type=2). +func (r *ProductRepository) UpdateGroup(ctx context.Context, update CategoryFieldUpdate, scope StoreScope) (*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if update.ExpectedVersion < 0 { + return nil, errors.New("expected_version must be non-negative") + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin update group: %w", err) + } + defer tx.Rollback() + + current, err := loadCategoryForUpdate(ctx, tx, update.ID, scope) + if err != nil { + return nil, err + } + if current.NodeType != 2 { + return nil, ErrInvalidProductGroup + } + if current.Version != update.ExpectedVersion { + return nil, ErrCategoryVersionConflict + } + updated, err := updateCategoryFields(ctx, tx, update) + if err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit update group: %w", err) + } + return updated, nil +} + +// DeleteGroup soft-deletes one product group and its bindings. Products are retained. +func (r *ProductRepository) DeleteGroup(ctx context.Context, groupID string, expectedVersion int32, scope StoreScope) (*GroupDeleteResult, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if expectedVersion < 0 { + return nil, errors.New("expected_version must be non-negative") + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin delete group: %w", err) + } + defer tx.Rollback() + + target, err := loadCategoryForUpdate(ctx, tx, groupID, scope) + if err != nil { + return nil, err + } + if target.NodeType != 2 || (target.Level != 1 && target.Level != 2) { + return nil, ErrInvalidProductGroup + } + if target.Version != expectedVersion { + return nil, ErrCategoryVersionConflict + } + targetID, err := parseID(target.ID, "group_id") + if err != nil { + return nil, err + } + groupIDs := []int64{targetID} + if target.Level == 1 { + rows, err := tx.QueryContext(ctx, ` +SELECT id, node_type, name, parent_id, level, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version +FROM product.catalog_category +WHERE parent_id = $1 AND store_id = $2 AND deleted_at IS NULL +FOR UPDATE +`, targetID, scope.StoreID) + if err != nil { + return nil, fmt.Errorf("load child groups for delete: %w", err) + } + for rows.Next() { + child, err := scanCategory(rows) + if err != nil { + rows.Close() + return nil, err + } + if child.NodeType != 2 || child.Level != 2 || child.ParentID != target.ID { + rows.Close() + return nil, ErrInvalidProductGroup + } + childID, err := parseID(child.ID, "group_id") + if err != nil { + rows.Close() + return nil, err + } + groupIDs = append(groupIDs, childID) + } + if err := rows.Err(); err != nil { + rows.Close() + return nil, fmt.Errorf("iterate child groups for delete: %w", err) + } + if err := rows.Close(); err != nil { + return nil, fmt.Errorf("close child groups for delete: %w", err) + } + } + placeholders := make([]string, len(groupIDs)) + args := make([]any, len(groupIDs)) + for index, id := range groupIDs { + placeholders[index] = fmt.Sprintf("$%d", index+1) + args[index] = id + } + whereIDs := strings.Join(placeholders, ", ") + result := &GroupDeleteResult{DeletedGroupID: target.ID} + if err := tx.QueryRowContext(ctx, fmt.Sprintf(` +SELECT COUNT(DISTINCT product_id), COUNT(*) +FROM product.product_catalog_bindings +WHERE category_id IN (%s) AND deleted_at IS NULL +`, whereIDs), args...).Scan(&result.UnboundProductCount, &result.UnboundBindingCount); err != nil { + return nil, fmt.Errorf("count group bindings for delete: %w", err) + } + if _, err := tx.ExecContext(ctx, fmt.Sprintf(` +UPDATE product.product_catalog_bindings +SET deleted_at = NOW(), updated_at = NOW() +WHERE category_id IN (%s) AND deleted_at IS NULL +`, whereIDs), args...); err != nil { + return nil, fmt.Errorf("delete group bindings: %w", err) + } + if target.Level == 1 { + if _, err := tx.ExecContext(ctx, ` +UPDATE product.catalog_category +SET deleted_at = NOW(), updated_at = NOW(), version = version + 1 +WHERE parent_id = $1 AND store_id = $2 AND node_type = 2 AND deleted_at IS NULL +`, targetID, scope.StoreID); err != nil { + return nil, fmt.Errorf("delete child groups: %w", err) + } + } + if _, err := tx.ExecContext(ctx, ` +UPDATE product.catalog_category +SET deleted_at = NOW(), updated_at = NOW(), version = version + 1 +WHERE id = $1 AND store_id = $2 AND node_type = 2 AND deleted_at IS NULL +`, targetID, scope.StoreID); err != nil { + return nil, fmt.Errorf("delete group: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit delete group: %w", err) + } + return result, nil +} + +func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string, scope StoreScope) (*CategoryRecord, error) { id, err := parseID(categoryID, "category_id") if err != nil { return nil, err } + if err := requireWriteScope(scope); err != nil { + return nil, err + } row := tx.QueryRowContext(ctx, ` SELECT id, node_type, name, parent_id, level, - COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version -FROM product.product_category -WHERE id = $1 -FOR UPDATE`, id) + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version +FROM product.catalog_category +WHERE id = $1 AND store_id = $2 AND deleted_at IS NULL +FOR UPDATE`, id, scope.StoreID) category, err := scanCategory(row) if errors.Is(err, sql.ErrNoRows) { return nil, ErrCategoryNodeNotFound @@ -685,30 +1375,40 @@ FOR UPDATE`, id) } func updateCategoryFields(ctx context.Context, tx *sql.Tx, update CategoryFieldUpdate) (*CategoryRecord, error) { - if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil { + if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil && update.CampaignID == nil { return nil, errors.New("category update has no fields") } id, err := parseID(update.ID, "category_id") if err != nil { return nil, err } + campaignID, err := nullableCategoryCampaignID(update.CampaignID) + if err != nil { + return nil, err + } row := tx.QueryRowContext(ctx, ` -UPDATE product.product_category +UPDATE product.catalog_category SET name = CASE WHEN $3 THEN $4 ELSE name END, image_ids = CASE WHEN $5 THEN $6 ELSE image_ids END, sort_num = CASE WHEN $7 THEN $8 ELSE sort_num END, status = CASE WHEN $9 THEN $10 ELSE status END, - version = version + 1 -WHERE id = $1 AND version = $2 + campaign_id = CASE WHEN $11 THEN $12 ELSE campaign_id END, + version = version + 1, + updated_at = NOW() +WHERE id = $1 AND version = $2 AND deleted_at IS NULL RETURNING id, node_type, name, parent_id, level, - COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version`, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, campaign_id, version`, id, update.ExpectedVersion, update.Name != nil, stringValue(update.Name), update.ImageIDs != nil, stringSliceOrEmpty(pointerStringSlice(update.ImageIDs)), update.SortNum != nil, int32Value(update.SortNum), update.Status != nil, int32Value(update.Status), + update.CampaignID != nil, campaignID, ) category, err := scanCategory(row) + if nameConflict := categoryNameConflictError(err); nameConflict != nil { + return nil, nameConflict + } if errors.Is(err, sql.ErrNoRows) { return nil, ErrCategoryVersionConflict } @@ -718,6 +1418,17 @@ RETURNING id, node_type, name, parent_id, level, return category, nil } +func nullableCategoryCampaignID(value *string) (sql.NullInt64, error) { + if value == nil || strings.TrimSpace(*value) == "" { + return sql.NullInt64{}, nil + } + id, err := parseID(strings.TrimSpace(*value), "campaign_id") + if err != nil { + return sql.NullInt64{}, err + } + return sql.NullInt64{Int64: id, Valid: true}, nil +} + func stringValue(value *string) string { if value == nil { return "" @@ -739,9 +1450,22 @@ func pointerStringSlice(value *[]string) []string { return *value } -// AddProductsToGroup binds every product to the requested category or product group in one transaction. +// AddProductsToGroup binds every product to a leaf product group in one transaction. // Existing bindings are retained and duplicate bindings are ignored. -func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string) error { +func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string, scope StoreScope) error { + return r.addProductsToCategoryNode(ctx, groupID, bindingIDs, productIDs, 2, -1, "group", scope) +} + +// AddProductsToCategory binds every product to a terminal catalog category at +// any level. Existing bindings are retained and duplicate bindings are ignored. +func (r *ProductRepository) AddProductsToCategory(ctx context.Context, categoryID string, bindingIDs, productIDs []string, scope StoreScope) error { + return r.addProductsToCategoryNode(ctx, categoryID, bindingIDs, productIDs, 1, -1, "category", scope) +} + +func (r *ProductRepository) addProductsToCategoryNode(ctx context.Context, nodeID string, bindingIDs, productIDs []string, nodeType, level int32, nodeLabel string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } if len(productIDs) == 0 { return errors.New("product_ids is required") } @@ -749,7 +1473,7 @@ func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID stri return errors.New("binding ids must match product ids") } - parsedGroupID, err := parseID(groupID, "group_id") + parsedNodeID, err := parseID(nodeID, nodeLabel+"_id") if err != nil { return err } @@ -768,20 +1492,30 @@ func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID stri tx, err := r.db.BeginTx(ctx, nil) if err != nil { - return fmt.Errorf("begin add products to group: %w", err) + return fmt.Errorf("begin add products to %s: %w", nodeLabel, err) } defer tx.Rollback() err = tx.QueryRowContext(ctx, ` -SELECT id -FROM product.product_category -WHERE id = $1 -`, parsedGroupID).Scan(&parsedGroupID) +SELECT c.id +FROM product.catalog_category c +WHERE c.id = $1 + AND c.node_type = $2 + AND c.store_id = $3 + AND c.deleted_at IS NULL + AND ($4 = 0 OR ($4 > 0 AND c.level = $4) OR ($4 = -1 AND NOT EXISTS ( + SELECT 1 FROM product.catalog_category child + WHERE child.parent_id = c.id + AND child.store_id = $3 + AND child.node_type = $2 + AND child.deleted_at IS NULL + ))) +`, parsedNodeID, nodeType, scope.StoreID, level).Scan(&parsedNodeID) if errors.Is(err, sql.ErrNoRows) { - return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID) + return fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, nodeID) } if err != nil { - return fmt.Errorf("query category or group node %s: %w", groupID, err) + return fmt.Errorf("query %s node %s: %w", nodeLabel, nodeID, err) } productPlaceholders := make([]string, len(parsedProductIDs)) @@ -790,29 +1524,31 @@ WHERE id = $1 productPlaceholders[i] = fmt.Sprintf("$%d", i+1) productArgs[i] = productID } + productArgs = append(productArgs, scope.StoreID) rows, err := tx.QueryContext(ctx, fmt.Sprintf(` SELECT id FROM product.products WHERE deleted_at IS NULL + AND store_id = $%d AND id IN (%s) -`, strings.Join(productPlaceholders, ", ")), productArgs...) +`, len(productArgs), strings.Join(productPlaceholders, ", ")), productArgs...) if err != nil { - return fmt.Errorf("query products for category or group binding: %w", err) + return fmt.Errorf("query products for %s binding: %w", nodeLabel, err) } foundProducts := make(map[int64]struct{}, len(parsedProductIDs)) for rows.Next() { var productID int64 if err := rows.Scan(&productID); err != nil { - return fmt.Errorf("scan product for category or group binding: %w", err) + return fmt.Errorf("scan product for %s binding: %w", nodeLabel, err) } foundProducts[productID] = struct{}{} } if err := rows.Err(); err != nil { - return fmt.Errorf("iterate products for category or group binding: %w", err) + return fmt.Errorf("iterate products for %s binding: %w", nodeLabel, err) } if err := rows.Close(); err != nil { - return fmt.Errorf("close products for category or group binding: %w", err) + return fmt.Errorf("close products for %s binding: %w", nodeLabel, err) } for i, productID := range parsedProductIDs { if _, ok := foundProducts[productID]; !ok { @@ -825,26 +1561,29 @@ WHERE deleted_at IS NULL for i, productID := range parsedProductIDs { base := i * 3 valuePlaceholders[i] = fmt.Sprintf("($%d, $%d, $%d)", base+1, base+2, base+3) - args = append(args, parsedBindingIDs[i], productID, parsedGroupID) + args = append(args, parsedBindingIDs[i], productID, parsedNodeID) } _, err = tx.ExecContext(ctx, fmt.Sprintf(` -INSERT INTO product.product_category_bindings (id, product_id, category_id) +INSERT INTO product.product_catalog_bindings (id, product_id, category_id) VALUES %s -ON CONFLICT (product_id, category_id) DO NOTHING +ON CONFLICT (product_id, category_id) WHERE deleted_at IS NULL DO NOTHING `, strings.Join(valuePlaceholders, ", ")), args...) if err != nil { - return fmt.Errorf("insert product category or group bindings: %w", err) + return fmt.Errorf("insert product %s bindings: %w", nodeLabel, err) } if err := tx.Commit(); err != nil { - return fmt.Errorf("commit add products to group: %w", err) + return fmt.Errorf("commit add products to %s: %w", nodeLabel, err) } return nil } // RemoveProductsFromGroup removes product bindings from the requested category or product group in one transaction. // Missing bindings are ignored so callers can safely retry the same request. -func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string) error { +func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID string, productIDs []string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } if len(productIDs) == 0 { return errors.New("product_ids is required") } @@ -868,10 +1607,21 @@ func (r *ProductRepository) RemoveProductsFromGroup(ctx context.Context, groupID defer tx.Rollback() err = tx.QueryRowContext(ctx, ` -SELECT id -FROM product.product_category -WHERE id = $1 -`, parsedGroupID).Scan(&parsedGroupID) +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 fmt.Errorf("%w: %s", ErrCategoryNodeNotFound, groupID) } @@ -887,9 +1637,11 @@ WHERE id = $1 args = append(args, productID) } _, err = tx.ExecContext(ctx, fmt.Sprintf(` -DELETE FROM product.product_category_bindings +UPDATE product.product_catalog_bindings +SET deleted_at = NOW(), updated_at = NOW() WHERE category_id = $1 AND product_id IN (%s) + AND deleted_at IS NULL `, strings.Join(placeholders, ", ")), args...) if err != nil { return fmt.Errorf("delete product category or group bindings: %w", err) @@ -918,9 +1670,20 @@ func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRe res, err := r.db.ExecContext(ctx, ` UPDATE product.products -SET spu_no = $2, title = $3, selling_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW() +SET spu_no = $2, + title = $3, + selling_point = $4, + status = $5, + cross_border = $6::jsonb, + presale_type = $7, + delivery_time_type = $8, + delivery_start_at = $9, + delivery_after_paid_days = $10, + purchase_limit_quantity = $11, + updated_at = NOW() WHERE id = $1 -`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs) +`, id, product.SPUNo, product.Title, product.SellingPoint, statusToDB(product.Status), attrs, + int16(product.PresaleType), int16(product.DeliveryTimeType), deliveryStartAtArgument(product), deliveryAfterPaidDaysArgument(product), product.PurchaseLimitQuantity) if err != nil { return fmt.Errorf("update product %s: %w", product.ID, err) } @@ -935,8 +1698,76 @@ WHERE id = $1 return nil } +// UpdateProductFreightChargeBySPUNo atomically updates only the freight +// configuration of one non-deleted, store-scoped product. It intentionally +// increments the product version so a concurrent full-product edit detects +// that its read snapshot is stale. +func (r *ProductRepository) UpdateProductFreightChargeBySPUNo(ctx context.Context, spuNo string, freightChargeType int32, freightFixedAmount int64, freightTemplateID string, scope StoreScope) (*ProductFreightChargeUpdate, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + spuNo = strings.TrimSpace(spuNo) + if spuNo == "" { + return nil, errors.New("spu_no is required") + } + if freightChargeType < 1 || freightChargeType > 2 { + return nil, errors.New("freight_charge_type must be 1 or 2") + } + if freightFixedAmount < 0 { + return nil, errors.New("freight_fixed_amount must be greater than or equal to 0") + } + + templateID := sql.NullInt64{} + if freightChargeType == 2 { + var err error + templateID, err = nullableID(freightTemplateID, "freight_template_id") + if err != nil { + return nil, err + } + if !templateID.Valid { + return nil, errors.New("freight_template_id is required when freight_charge_type is 2") + } + } + + result := &ProductFreightChargeUpdate{} + var productID int64 + var storedTemplateID sql.NullInt64 + err := r.db.QueryRowContext(ctx, ` +UPDATE product.products +SET freight_charge_type = $3, + freight_fixed_amount = $4, + freight_template_id = $5, + version = version + 1, + updated_at = NOW() +WHERE store_id = $1 AND spu_no = $2 AND deleted_at IS NULL +RETURNING id, spu_no, freight_charge_type, freight_fixed_amount, freight_template_id, version, updated_at +`, scope.StoreID, spuNo, int16(freightChargeType), freightFixedAmount, templateID).Scan( + &productID, + &result.SPUNo, + &result.FreightChargeType, + &result.FreightFixedAmount, + &storedTemplateID, + &result.Version, + &result.UpdatedAt, + ) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductNotFound + } + if err != nil { + return nil, fmt.Errorf("update product freight charge by spu_no: %w", err) + } + result.ProductID = formatID(productID) + if storedTemplateID.Valid { + result.FreightTemplateID = formatID(storedTemplateID.Int64) + } + return result, nil +} + // UpdateProductWithSKUChange atomically persists a merged SPU update and an optional SKU operation. func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, input ProductUpdateInput) (*SKUChangeResult, error) { + if err := requireWriteScope(input.Scope); err != nil { + return nil, err + } if input.ExpectedVersion < 0 { return nil, fmt.Errorf("expected product version must be non-negative") } @@ -948,6 +1779,10 @@ func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, inpu if err != nil { return nil, err } + categoryProperties, err := productCategoryPropertiesJSON(input.Product) + if err != nil { + return nil, err + } brandID, err := nullableID(input.Product.BrandID, "brand_id") if err != nil { return nil, err @@ -972,9 +1807,9 @@ func (r *ProductRepository) UpdateProductWithSKUChange(ctx context.Context, inpu err = tx.QueryRowContext(ctx, ` SELECT status, version FROM product.products -WHERE id = $1 AND deleted_at IS NULL +WHERE id = $1 AND deleted_at IS NULL AND store_id = $2 FOR UPDATE -`, productID).Scan(¤tStatus, ¤tVersion) +`, productID, input.Scope.StoreID).Scan(¤tStatus, ¤tVersion) if errors.Is(err, sql.ErrNoRows) { return nil, ErrProductNotFound } @@ -985,7 +1820,17 @@ FOR UPDATE return nil, ErrProductVersionConflict } if input.LeafCategoryIDs != nil { - if err := replaceProductLeafCategoryBindings(ctx, tx, input.Product.ID, *input.LeafCategoryIDs, input.CategoryBindingIDs); err != nil { + if err := replaceProductLeafCategoryBindings(ctx, tx, input.Product.ID, *input.LeafCategoryIDs, input.CategoryBindingIDs, input.Scope); err != nil { + return nil, err + } + } + if input.GroupIDs != nil { + if err := replaceProductGroupBindings(ctx, tx, input.Product.ID, *input.GroupIDs, input.GroupBindingIDs, input.Scope); err != nil { + return nil, err + } + } + if input.ProductCategoryIDs != nil { + if err := replaceProductStandardCategoryBindings(ctx, tx, input.Product.ID, *input.ProductCategoryIDs, input.ProductCategoryBindingIDs, input.Scope); err != nil { return nil, err } } @@ -1003,22 +1848,32 @@ SET title = $2, image_ids = $6, detail_html = $7, member_discount_enabled = $8, - goods_type = $9, - service_guarantees = $10, - cross_border = $11::jsonb, - freight_charge_type = $12, - freight_fixed_amount = $13, - freight_template_id = $14, - sale_time_type = $15, - scheduled_sale_time = $16, + is_distribution_product = $9, + distribution_product_detail = $10::jsonb, + goods_type = $11, + service_guarantees = $12, + cross_border = $13::jsonb, + category_properties = $14::jsonb, + freight_charge_type = $15, + freight_fixed_amount = $16, + freight_template_id = $17, + sale_time_type = $18, + scheduled_sale_time = $19, + presale_type = $20, + delivery_time_type = $21, + delivery_start_at = $22, + delivery_after_paid_days = $23, + purchase_limit_quantity = $24, version = version + 1, updated_at = NOW() -WHERE id = $1 AND version = $17 AND deleted_at IS NULL +WHERE id = $1 AND version = $25 AND deleted_at IS NULL AND store_id = $26 `, productID, input.Product.Title, input.Product.SellingPoint, brandID, supplierID, - stringSliceOrEmpty(input.Product.ImageIDs), input.Product.DetailHTML, input.Product.MemberDiscountEnabled, - int16(input.Product.GoodsType), stringSliceOrEmpty(input.Product.ServiceGuarantees), attrs, + stringSliceOrEmpty(input.Product.ImageIDs), input.Product.DetailHTML, input.Product.MemberDiscountEnabled, input.Product.IsDistributionProduct, + input.Product.DistributionProductDetailJSON, int16(input.Product.GoodsType), stringSliceOrEmpty(input.Product.ServiceGuarantees), attrs, categoryProperties, int16(input.Product.FreightChargeType), input.Product.FreightFixedAmount, freightTemplateID, - int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, input.ExpectedVersion); err != nil { + int16(input.Product.SaleTimeType), input.Product.ScheduledSaleTime, + int16(input.Product.PresaleType), int16(input.Product.DeliveryTimeType), deliveryStartAtArgument(input.Product), deliveryAfterPaidDaysArgument(input.Product), input.Product.PurchaseLimitQuantity, + input.ExpectedVersion, input.Scope.StoreID); err != nil { return nil, fmt.Errorf("update product %s: %w", input.Product.ID, err) } @@ -1052,7 +1907,7 @@ WHERE id = $1 AND version = $17 AND deleted_at IS NULL default: return nil, fmt.Errorf("unsupported sku change mode") } - if err := autoOffSaleIfNoSellableSKU(ctx, tx, productID); err != nil { + if err := autoMarkProductSoldOut(ctx, tx, productID); err != nil { return nil, err } } @@ -1063,7 +1918,10 @@ WHERE id = $1 AND version = $17 AND deleted_at IS NULL return result, nil } -func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, leafCategoryIDs []string, bindingIDs []string) error { +func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, leafCategoryIDs []string, bindingIDs []string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } if len(leafCategoryIDs) != len(bindingIDs) { return errors.New("leaf category ids and category binding ids must have the same length") } @@ -1079,7 +1937,7 @@ func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, product return err } if _, duplicate := seenCategoryIDs[parsedLeafCategoryIDs[index]]; duplicate { - return errors.New("leaf_category_ids must not contain duplicates") + return errors.New("leaf_catalog_category_ids must not contain duplicates") } seenCategoryIDs[parsedLeafCategoryIDs[index]] = struct{}{} if _, err := parseID(bindingIDs[index], "category binding id"); err != nil { @@ -1095,13 +1953,21 @@ func replaceProductLeafCategoryBindings(ctx context.Context, tx *sql.Tx, product args[index] = categoryID } rows, err := tx.QueryContext(ctx, fmt.Sprintf(` -SELECT id -FROM product.product_category -WHERE node_type = 1 - AND level = 2 - AND id IN (%s) +SELECT c.id +FROM product.catalog_category c +WHERE c.node_type = 1 + AND c.store_id = $%d + AND c.id IN (%s) + 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 = c.store_id + AND child.node_type = 1 + AND child.deleted_at IS NULL + ) FOR KEY SHARE -`, strings.Join(placeholders, ", ")), args...) +`, len(args)+1, strings.Join(placeholders, ", ")), append(args, scope.StoreID)...) if err != nil { return fmt.Errorf("validate leaf categories: %w", err) } @@ -1127,13 +1993,16 @@ FOR KEY SHARE } if _, err := tx.ExecContext(ctx, ` -DELETE FROM product.product_category_bindings AS b -USING product.product_category AS c +UPDATE product.product_catalog_bindings AS b +SET deleted_at = NOW(), updated_at = NOW() +FROM product.catalog_category AS c WHERE b.product_id = $1 AND b.category_id = c.id AND c.node_type = 1 - AND c.level = 2 -`, parsedProductID); err != nil { + AND c.store_id = $2 + AND b.deleted_at IS NULL + AND c.deleted_at IS NULL +`, parsedProductID, scope.StoreID); err != nil { return fmt.Errorf("delete product leaf category bindings: %w", err) } for index, categoryID := range leafCategoryIDs { @@ -1144,12 +2013,265 @@ WHERE b.product_id = $1 return nil } +// replaceProductGroupBindings replaces only the product's group bindings. It +// deliberately leaves category bindings intact. +func replaceProductGroupBindings(ctx context.Context, tx *sql.Tx, productID string, groupIDs []string, bindingIDs []string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } + if len(groupIDs) != len(bindingIDs) { + return errors.New("group ids and group binding ids must have the same length") + } + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return err + } + parsedGroupIDs := make([]int64, len(groupIDs)) + seenGroupIDs := make(map[int64]struct{}, len(groupIDs)) + for index, groupID := range groupIDs { + parsedGroupIDs[index], err = parseID(groupID, "group_id") + if err != nil { + return err + } + if _, duplicate := seenGroupIDs[parsedGroupIDs[index]]; duplicate { + return errors.New("group_ids must not contain duplicates") + } + seenGroupIDs[parsedGroupIDs[index]] = struct{}{} + if _, err := parseID(bindingIDs[index], "group binding id"); err != nil { + return err + } + } + + if len(parsedGroupIDs) > 0 { + placeholders := make([]string, len(parsedGroupIDs)) + args := make([]any, len(parsedGroupIDs)) + for index, groupID := range parsedGroupIDs { + placeholders[index] = fmt.Sprintf("$%d", index+1) + args[index] = groupID + } + rows, err := tx.QueryContext(ctx, fmt.Sprintf(` +SELECT c.id +FROM product.catalog_category AS c +WHERE c.node_type = 2 + AND c.store_id = $%d + AND c.id IN (%s) + 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 = $%d + AND child.node_type = 2 + AND child.deleted_at IS NULL + ) +FOR KEY SHARE +`, len(args)+1, strings.Join(placeholders, ", "), len(args)+1), append(args, scope.StoreID)...) + if err != nil { + return fmt.Errorf("validate product groups: %w", err) + } + found := make(map[int64]struct{}, len(parsedGroupIDs)) + for rows.Next() { + var groupID int64 + if err := rows.Scan(&groupID); err != nil { + rows.Close() + return fmt.Errorf("scan product group: %w", err) + } + found[groupID] = struct{}{} + } + if err := rows.Err(); err != nil { + rows.Close() + return fmt.Errorf("iterate product groups: %w", err) + } + if err := rows.Close(); err != nil { + return fmt.Errorf("close product groups: %w", err) + } + if len(found) != len(parsedGroupIDs) { + return ErrInvalidProductGroup + } + } + + if _, err := tx.ExecContext(ctx, ` +UPDATE product.product_catalog_bindings AS b +SET deleted_at = NOW(), updated_at = NOW() +FROM product.catalog_category AS c +WHERE b.product_id = $1 + AND b.category_id = c.id + AND c.node_type = 2 + AND c.store_id = $2 + AND b.deleted_at IS NULL + AND c.deleted_at IS NULL +`, parsedProductID, scope.StoreID); err != nil { + return fmt.Errorf("delete product group bindings: %w", err) + } + for index, groupID := range groupIDs { + if err := insertCategoryBinding(ctx, tx, bindingIDs[index], productID, groupID); err != nil { + return err + } + } + return nil +} + +// replaceProductStandardCategoryBindings replaces the active global standard +// product-category bindings for one store product. It is intentionally +// transaction-scoped so product, SKU, and binding changes commit or roll back +// as one unit. +func replaceProductStandardCategoryBindings(ctx context.Context, tx *sql.Tx, productID string, categoryIDs []string, bindingIDs []string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } + if len(categoryIDs) != len(bindingIDs) { + return errors.New("product category ids and binding ids must have the same length") + } + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return err + } + parsedCategoryIDs := make([]int64, len(categoryIDs)) + seenCategoryIDs := make(map[int64]struct{}, len(categoryIDs)) + for index, categoryID := range categoryIDs { + parsedCategoryIDs[index], err = parseID(categoryID, "product_category_id") + if err != nil { + return err + } + if _, duplicate := seenCategoryIDs[parsedCategoryIDs[index]]; duplicate { + return errors.New("product_category_ids must not contain duplicates") + } + seenCategoryIDs[parsedCategoryIDs[index]] = struct{}{} + if _, err := parseID(bindingIDs[index], "product category binding id"); err != nil { + return err + } + } + + if len(parsedCategoryIDs) > 0 { + placeholders := make([]string, len(parsedCategoryIDs)) + args := make([]any, len(parsedCategoryIDs)) + for index, categoryID := range parsedCategoryIDs { + placeholders[index] = fmt.Sprintf("$%d", index+1) + args[index] = categoryID + } + rows, err := tx.QueryContext(ctx, fmt.Sprintf(` +SELECT c.id +FROM product.product_category AS c +WHERE c.id IN (%s) + AND c.deleted_at IS NULL + AND c.status = 1 + AND NOT EXISTS ( + SELECT 1 + FROM product.product_category AS child + WHERE child.parent_id = c.id AND child.deleted_at IS NULL + ) +ORDER BY c.id +FOR UPDATE +`, strings.Join(placeholders, ", ")), args...) + if err != nil { + return fmt.Errorf("validate standard product categories: %w", err) + } + found := make(map[int64]struct{}, len(parsedCategoryIDs)) + for rows.Next() { + var categoryID int64 + if err := rows.Scan(&categoryID); err != nil { + rows.Close() + return fmt.Errorf("scan standard product category: %w", err) + } + found[categoryID] = struct{}{} + } + if err := rows.Err(); err != nil { + rows.Close() + return fmt.Errorf("iterate standard product categories: %w", err) + } + if err := rows.Close(); err != nil { + return fmt.Errorf("close standard product categories: %w", err) + } + if len(found) != len(parsedCategoryIDs) { + return ErrInvalidProductCategory + } + } + + deleteArgs := []any{parsedProductID, scope.TenantID, scope.StoreID} + deleteSQL := ` +UPDATE product.product_category_bindings +SET deleted_at = NOW(), updated_at = NOW() +WHERE product_id = $1 + AND tenant_id = $2 + AND store_id = $3 + AND deleted_at IS NULL` + if len(parsedCategoryIDs) > 0 { + placeholders := make([]string, len(parsedCategoryIDs)) + for index, categoryID := range parsedCategoryIDs { + placeholders[index] = fmt.Sprintf("$%d", index+4) + deleteArgs = append(deleteArgs, categoryID) + } + deleteSQL += "\n AND product_category_id NOT IN (" + strings.Join(placeholders, ", ") + ")" + } + if _, err := tx.ExecContext(ctx, deleteSQL, deleteArgs...); err != nil { + return fmt.Errorf("soft delete standard product category bindings: %w", err) + } + + for index, categoryID := range parsedCategoryIDs { + var active bool + if err := tx.QueryRowContext(ctx, ` +SELECT EXISTS( + SELECT 1 + FROM product.product_category_bindings + WHERE product_id = $1 + AND tenant_id = $2 + AND store_id = $3 + AND product_category_id = $4 + AND deleted_at IS NULL +) +`, parsedProductID, scope.TenantID, scope.StoreID, categoryID).Scan(&active); err != nil { + return fmt.Errorf("check active standard product category binding: %w", err) + } + if active { + continue + } + result, err := tx.ExecContext(ctx, ` +UPDATE product.product_category_bindings +SET deleted_at = NULL, updated_at = NOW() +WHERE id = ( + SELECT id + FROM product.product_category_bindings + WHERE product_id = $1 + AND tenant_id = $2 + AND store_id = $3 + AND product_category_id = $4 + AND deleted_at IS NOT NULL + ORDER BY updated_at DESC, id DESC + LIMIT 1 +) +`, parsedProductID, scope.TenantID, scope.StoreID, categoryID) + if err != nil { + return fmt.Errorf("restore standard product category binding: %w", err) + } + affected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("standard product category binding rows affected: %w", err) + } + if affected == 0 { + bindingID, err := parseID(bindingIDs[index], "product category binding id") + if err != nil { + return err + } + if _, err := 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) +`, bindingID, scope.TenantID, scope.StoreID, parsedProductID, categoryID); err != nil { + return fmt.Errorf("insert standard product category binding: %w", err) + } + } + } + return nil +} + // UpdateProductStatus changes the product lifecycle state using optimistic locking. -func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32) (*ProductStatusUpdate, error) { +func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID string, next productv1.ProductStatus, expectedVersion int32, scope StoreScope) (*ProductStatusUpdate, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } if expectedVersion < 0 { return nil, fmt.Errorf("expected product version must be non-negative") } - if next != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && next != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && next != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { + if next != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && next != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && next != productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT { return nil, fmt.Errorf("unsupported product status") } id, err := parseID(productID, "product id") @@ -1167,9 +2289,9 @@ func (r *ProductRepository) UpdateProductStatus(ctx context.Context, productID s err = tx.QueryRowContext(ctx, ` SELECT status, version FROM product.products -WHERE id = $1 AND deleted_at IS NULL +WHERE id = $1 AND deleted_at IS NULL AND store_id = $2 FOR UPDATE -`, id).Scan(&previousDBStatus, ¤tVersion) +`, id, scope.StoreID).Scan(&previousDBStatus, ¤tVersion) if errors.Is(err, sql.ErrNoRows) { return nil, ErrProductNotFound } @@ -1200,9 +2322,9 @@ FOR UPDATE if err := tx.QueryRowContext(ctx, ` UPDATE product.products SET status = $2, version = version + 1, updated_at = NOW() -WHERE id = $1 AND version = $3 AND deleted_at IS NULL +WHERE id = $1 AND version = $3 AND deleted_at IS NULL AND store_id = $4 RETURNING version, updated_at -`, id, statusToDB(next), expectedVersion).Scan(&result.Version, &result.UpdatedAt); err != nil { +`, id, statusToDB(next), expectedVersion, scope.StoreID).Scan(&result.Version, &result.UpdatedAt); err != nil { return nil, fmt.Errorf("update product status %s: %w", productID, err) } if err := tx.Commit(); err != nil { @@ -1211,6 +2333,95 @@ RETURNING version, updated_at return result, nil } +// TransferProductStoreResult is the identity after a same-tenant store move. +type TransferProductStoreResult struct { + ProductID string + TenantID int64 + StoreID int64 +} + +// TransferProductStore moves a product and its SKUs to another store. Tenant stays unchanged. +// Category bindings are dropped because categories are store-scoped. +func (r *ProductRepository) TransferProductStore(ctx context.Context, productID string, targetStoreID int64, scope StoreScope) (*TransferProductStoreResult, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if targetStoreID <= 0 { + return nil, fmt.Errorf("target store id must be a positive snowflake id") + } + if targetStoreID == scope.StoreID { + return nil, ErrSameStore + } + id, err := parseID(productID, "product id") + if err != nil { + return nil, err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin transfer product store: %w", err) + } + defer tx.Rollback() + + var tenantID int64 + var spuNo string + err = tx.QueryRowContext(ctx, ` +SELECT tenant_id, spu_no +FROM product.products +WHERE id = $1 AND deleted_at IS NULL AND store_id = $2 AND tenant_id = $3 +FOR UPDATE +`, id, scope.StoreID, scope.TenantID).Scan(&tenantID, &spuNo) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrProductNotFound + } + if err != nil { + return nil, fmt.Errorf("lock product %s: %w", productID, err) + } + + if strings.TrimSpace(spuNo) != "" { + var taken int + if err := tx.QueryRowContext(ctx, ` +SELECT 1 +FROM product.products +WHERE store_id = $1 AND spu_no = $2 AND deleted_at IS NULL AND id <> $3 +LIMIT 1 +`, targetStoreID, spuNo, id).Scan(&taken); err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("check target spu_no: %w", err) + } + if taken == 1 { + return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo) + } + } + + if _, err := tx.ExecContext(ctx, ` +UPDATE product.products +SET store_id = $2, version = version + 1, updated_at = NOW() +WHERE id = $1 AND store_id = $3 AND tenant_id = $4 AND deleted_at IS NULL +`, id, targetStoreID, scope.StoreID, tenantID); err != nil { + if isPostgresConstraintError(err, "23505", "uq_products_store_spu_no") { + return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, spuNo) + } + return nil, fmt.Errorf("update product store: %w", err) + } + if _, err := tx.ExecContext(ctx, ` +UPDATE product.product_items +SET store_id = $2 +WHERE product_id = $1 AND store_id = $3 +`, id, targetStoreID, scope.StoreID); err != nil { + return nil, fmt.Errorf("update sku store: %w", err) + } + if _, err := tx.ExecContext(ctx, ` +UPDATE product.product_catalog_bindings +SET deleted_at = NOW(), updated_at = NOW() +WHERE product_id = $1 AND deleted_at IS NULL +`, id); err != nil { + return nil, fmt.Errorf("detach product categories: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit transfer product store: %w", err) + } + return &TransferProductStoreResult{ProductID: productID, TenantID: tenantID, StoreID: targetStoreID}, nil +} + func updateCurrentSKU(ctx context.Context, tx *sql.Tx, productID int64, input SKUUpdate) error { if input.ExpectedSKUVersion < 0 || input.ExpectedInventoryVersion < 0 { return fmt.Errorf("expected sku and inventory versions must be non-negative") @@ -1241,7 +2452,7 @@ FOR UPDATE return ErrSKUVersionConflict } - if input.Name != nil || input.Price != nil || input.Status != nil || input.ImageIDs != nil { + if input.Name != nil || input.Price != nil || input.SupplyPriceSet || input.WeightKgSet || input.Barcode != nil || input.Status != nil || input.ImageIDs != nil { sets := []string{"updated_at = NOW()", "version = version + 1"} args := []any{skuID, productID} argIndex := 3 @@ -1261,6 +2472,27 @@ FOR UPDATE args = append(args, *input.Price) argIndex++ } + if input.SupplyPriceSet { + if input.SupplyPrice != nil && *input.SupplyPrice < 0 { + return fmt.Errorf("sku supply_price must be greater than or equal to 0") + } + sets = append(sets, fmt.Sprintf("supply_price = $%d", argIndex)) + args = append(args, nullableInt64(input.SupplyPrice)) + argIndex++ + } + if input.WeightKgSet { + if input.WeightKg != nil && *input.WeightKg < 0 { + return fmt.Errorf("sku weight_kg must be greater than or equal to 0") + } + sets = append(sets, fmt.Sprintf("weight_kg = $%d", argIndex)) + args = append(args, nullableFloat64(input.WeightKg)) + argIndex++ + } + if input.Barcode != nil { + sets = append(sets, fmt.Sprintf("barcode = $%d", argIndex)) + args = append(args, nullString(strings.TrimSpace(*input.Barcode))) + argIndex++ + } if input.Status != nil { if *input.Status != 0 && *input.Status != 1 { return fmt.Errorf("sku status must be 0 or 1") @@ -1369,8 +2601,10 @@ SELECT EXISTS( return exists, nil } -// autoOffSaleIfNoSellableSKU transitions an on-sale product to OFF_SALE only; it never auto-relists. -func autoOffSaleIfNoSellableSKU(ctx context.Context, tx *sql.Tx, productID int64) error { +// autoMarkProductSoldOut transitions an on-sale product to SOLD_OUT (status 3) +// when no SKU can be sold. It never auto-relists: +// replenishment alone must not undo an explicit or automatic sold-out state. +func autoMarkProductSoldOut(ctx context.Context, tx *sql.Tx, productID int64) error { _, err := tx.ExecContext(ctx, ` UPDATE product.products p SET status = $2, version = version + 1, updated_at = NOW() @@ -1387,9 +2621,9 @@ WHERE p.id = $1 AND pi.status = 1 AND inv.stock_quantity > inv.locked_quantity ) -`, productID, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE)) +`, productID, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE)) if err != nil { - return fmt.Errorf("auto off-sale product %s: %w", formatID(productID), err) + return fmt.Errorf("auto mark product sold out %s: %w", formatID(productID), err) } return nil } @@ -1454,10 +2688,12 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error defer tx.Rollback() err = tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status) -VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8) +INSERT INTO product.product_items (id, product_id, sku_no, name, price, supply_price, weight_kg, barcode, image_ids, attributes, status, tenant_id, store_id) +SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, $11, p.tenant_id, p.store_id +FROM product.products p +WHERE p.id = $2 RETURNING id -`, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID) +`, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, nullableInt64(sku.SupplyPrice), nullableFloat64(sku.WeightKg), nullString(sku.Barcode), stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID) if err != nil { return fmt.Errorf("insert sku: %w", err) } @@ -1517,7 +2753,10 @@ WHERE id = $1 AND is_archived = FALSE } // LockInventory atomically reserves quantity when stock_quantity - locked_quantity >= quantity. -func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32) (*InventoryRecord, error) { +func (r *ProductRepository) LockInventory(ctx context.Context, skuID string, quantity int32, scope StoreScope) (*InventoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } if quantity <= 0 { return nil, fmt.Errorf("quantity must be positive") } @@ -1543,15 +2782,20 @@ WHERE pi.id = $1 AND pi.is_archived = FALSE AND pi.status = 1 AND p.deleted_at IS NULL + AND p.store_id = $2 FOR UPDATE OF p -`, id).Scan(&productID, &productStatus) +`, id, scope.StoreID).Scan(&productID, &productStatus) if errors.Is(err, sql.ErrNoRows) { return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrSKUNotFound) } if err != nil { return nil, fmt.Errorf("lock product for inventory %s: %w", skuID, err) } - if statusFromDB(productStatus) != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE { + productLifecycleStatus := statusFromDB(productStatus) + if productLifecycleStatus == productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT { + return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrProductSoldOut) + } + if productLifecycleStatus != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE { return nil, fmt.Errorf("lock inventory %s: %w", skuID, ErrProductNotOnSale) } row := tx.QueryRowContext(ctx, ` @@ -1585,7 +2829,7 @@ RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, c if err != nil { return nil, fmt.Errorf("lock inventory %s: %w", skuID, err) } - if err := autoOffSaleIfNoSellableSKU(ctx, tx, productID); err != nil { + if err := autoMarkProductSoldOut(ctx, tx, productID); err != nil { return nil, err } if err := tx.Commit(); err != nil { @@ -1595,16 +2839,22 @@ RETURNING id, sku_id, stock_quantity, locked_quantity, sold_quantity, version, c } // ConfirmInventory converts locked stock to sold stock after payment succeeds. -func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment) ([]*InventoryRecord, error) { - return r.applyInventoryAdjustments(ctx, orderID, "confirm", items) +func (r *ProductRepository) ConfirmInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + return r.applyInventoryAdjustments(ctx, orderID, "confirm", items, scope) } // ReleaseInventory releases locked stock when a pending order is cancelled or expires. -func (r *ProductRepository) ReleaseInventory(ctx context.Context, orderID string, items []InventoryAdjustment) ([]*InventoryRecord, error) { - return r.applyInventoryAdjustments(ctx, orderID, "release", items) +func (r *ProductRepository) ReleaseInventory(ctx context.Context, orderID string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + return r.applyInventoryAdjustments(ctx, orderID, "release", items, scope) } -func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, orderID, action string, items []InventoryAdjustment) ([]*InventoryRecord, error) { +func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, orderID, action string, items []InventoryAdjustment, scope StoreScope) ([]*InventoryRecord, error) { parsedOrderID, err := parseID(orderID, "order id") if err != nil { return nil, err @@ -1626,6 +2876,19 @@ func (r *ProductRepository) applyInventoryAdjustments(ctx context.Context, order if err != nil { return nil, err } + var owned int + err = tx.QueryRowContext(ctx, ` +SELECT 1 +FROM product.product_items pi +JOIN product.products p ON p.id = pi.product_id +WHERE pi.id = $1 AND p.store_id = $2 AND p.deleted_at IS NULL +`, skuID, scope.StoreID).Scan(&owned) + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("%s inventory %s: %w", action, formatID(skuID), ErrSKUNotFound) + } + if err != nil { + return nil, fmt.Errorf("verify %s inventory store %s: %w", action, formatID(skuID), err) + } var inserted bool err = tx.QueryRowContext(ctx, ` @@ -1841,8 +3104,11 @@ WHERE id = $1 AND deleted_at IS NULL } // GetProduct loads an SPU and its SKU list by product ID. -func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (*ProductRecord, []SKURecord, error) { - product, err := r.loadProductByID(ctx, productID) +func (r *ProductRepository) GetProduct(ctx context.Context, productID string, scope StoreScope) (*ProductRecord, []SKURecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, nil, err + } + product, err := r.loadProductByID(ctx, productID, scope) if err != nil { return nil, nil, err } @@ -1851,50 +3117,181 @@ func (r *ProductRepository) GetProduct(ctx context.Context, productID string) (* if err != nil { return nil, nil, err } - leafCategoryIDs, err := r.listProductLeafCategoryIDs(ctx, productID) + leafCategoryIDs, err := r.listProductLeafCategoryIDs(ctx, productID, scope) if err != nil { return nil, nil, err } product.LeafCategoryIDs = leafCategoryIDs + groupIDs, err := r.listProductGroupIDs(ctx, productID, scope) + if err != nil { + return nil, nil, err + } + product.GroupIDs = groupIDs + productCategoryIDs, err := r.listProductCategoryIDs(ctx, productID, scope) + if err != nil { + return nil, nil, err + } + product.ProductCategoryIDs = productCategoryIDs + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return nil, nil, err + } + productCategorySummaries, err := r.loadProductCategorySummaries(ctx, []int64{parsedProductID}, scope) + if err != nil { + return nil, nil, err + } + product.ProductCategories = productCategorySummaries[productID] return product, skus[productID], nil } +// GetProductTotalSoldQuantity returns the lifetime paid-unit count for one +// product in the current store. Retired SKU rows are intentionally included: +// removing a SKU from the storefront must not make the product's cumulative +// sales count decrease. +func (r *ProductRepository) GetProductTotalSoldQuantity(ctx context.Context, productID string, scope StoreScope) (int64, error) { + if err := requireWriteScope(scope); err != nil { + return 0, err + } + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return 0, err + } + + var soldQuantity int64 + err = r.db.QueryRowContext(ctx, ` +SELECT COALESCE(SUM(COALESCE(inv.sold_quantity, 0)), 0) +FROM product.product_items AS pi +LEFT JOIN product.product_item_inventory AS inv ON inv.sku_id = pi.id +WHERE pi.product_id = $1 + AND pi.store_id = $2 +`, parsedProductID, scope.StoreID).Scan(&soldQuantity) + if err != nil { + return 0, fmt.Errorf("query product total sold quantity: %w", err) + } + return soldQuantity, nil +} + +// ListProductSKUStocks loads every current SKU and its inventory pool quantity for one product. +// Archived and soft-deleted SKU rows are historical records and are deliberately excluded. +func (r *ProductRepository) ListProductSKUStocks(ctx context.Context, productID string, scope StoreScope) ([]ProductSKUStockRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return nil, err + } + + var exists bool + err = r.db.QueryRowContext(ctx, ` +SELECT EXISTS( + SELECT 1 + FROM product.products + WHERE id = $1 + AND store_id = $2 + AND deleted_at IS NULL +) +`, parsedProductID, scope.StoreID).Scan(&exists) + if err != nil { + return nil, fmt.Errorf("check product for sku list: %w", err) + } + if !exists { + return nil, ErrProductNotFound + } + + rows, err := r.db.QueryContext(ctx, ` +SELECT pi.id, + pi.name, + COALESCE(inv.stock_quantity, 0), + pi.supply_price +FROM product.product_items AS pi +LEFT JOIN product.product_item_inventory AS inv ON inv.sku_id = pi.id +WHERE pi.product_id = $1 + AND pi.store_id = $2 + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE +ORDER BY pi.created_at ASC, pi.id ASC +`, parsedProductID, scope.StoreID) + if err != nil { + return nil, fmt.Errorf("query product sku stocks: %w", err) + } + defer rows.Close() + + skus := make([]ProductSKUStockRecord, 0) + for rows.Next() { + var ( + sku ProductSKUStockRecord + id int64 + ) + var supplyPrice sql.NullInt64 + if err := rows.Scan(&id, &sku.Name, &sku.StockQuantity, &supplyPrice); err != nil { + return nil, fmt.Errorf("scan product sku stock: %w", err) + } + sku.ID = formatID(id) + if supplyPrice.Valid { + value := supplyPrice.Int64 + sku.SupplyPrice = &value + } + skus = append(skus, sku) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate product sku stocks: %w", err) + } + return skus, nil +} + // GetProductBySKU loads the SPU that owns skuID (product_items.id is the SKU PK). -func (r *ProductRepository) GetProductBySKU(ctx context.Context, skuID string) (*ProductRecord, []SKURecord, error) { +func (r *ProductRepository) GetProductBySKU(ctx context.Context, skuID string, scope StoreScope) (*ProductRecord, []SKURecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, nil, err + } parsedSKU, err := parseID(skuID, "sku_id") if err != nil { return nil, nil, err } var productID int64 err = r.db.QueryRowContext(ctx, ` -SELECT product_id -FROM product.product_items -WHERE id = $1 AND deleted_at IS NULL AND is_archived = FALSE -`, parsedSKU).Scan(&productID) +SELECT pi.product_id +FROM product.product_items pi +JOIN product.products p ON p.id = pi.product_id +WHERE pi.id = $1 AND pi.deleted_at IS NULL AND pi.is_archived = FALSE + AND p.deleted_at IS NULL AND p.store_id = $2 +`, parsedSKU, scope.StoreID).Scan(&productID) if errors.Is(err, sql.ErrNoRows) { return nil, nil, ErrSKUNotFound } if err != nil { return nil, nil, fmt.Errorf("lookup product by sku: %w", err) } - return r.GetProduct(ctx, formatID(productID)) + return r.GetProduct(ctx, formatID(productID), scope) } -func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string) ([]string, error) { +func (r *ProductRepository) listProductLeafCategoryIDs(ctx context.Context, productID string, scope StoreScope) ([]string, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } parsedProductID, err := parseID(productID, "product_id") if err != nil { return nil, err } rows, err := r.db.QueryContext(ctx, ` SELECT c.id -FROM product.product_category_bindings AS b -JOIN product.product_category AS c ON c.id = b.category_id +FROM product.product_catalog_bindings AS b +JOIN product.catalog_category AS c ON c.id = b.category_id AND c.deleted_at IS NULL WHERE b.product_id = $1 + AND b.deleted_at IS NULL AND c.node_type = 1 - AND c.level = 2 + AND c.store_id = $2 + AND NOT EXISTS ( + SELECT 1 FROM product.catalog_category child + WHERE child.parent_id = c.id + AND child.store_id = c.store_id + AND child.node_type = 1 + AND child.deleted_at IS NULL + ) ORDER BY c.sort_num, c.id -`, parsedProductID) +`, parsedProductID, scope.StoreID) if err != nil { return nil, fmt.Errorf("list product leaf category ids: %w", err) } @@ -1913,9 +3310,85 @@ ORDER BY c.sort_num, c.id return leafCategoryIDs, nil } +func (r *ProductRepository) listProductGroupIDs(ctx context.Context, productID string, scope StoreScope) ([]string, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return nil, err + } + rows, err := r.db.QueryContext(ctx, ` +SELECT c.id +FROM product.product_catalog_bindings AS b +JOIN product.catalog_category AS c ON c.id = b.category_id AND c.deleted_at IS NULL +WHERE b.product_id = $1 + AND b.deleted_at IS NULL + AND c.node_type = 2 + AND c.store_id = $2 +ORDER BY c.sort_num, c.id +`, parsedProductID, scope.StoreID) + if err != nil { + return nil, fmt.Errorf("list product group ids: %w", err) + } + defer rows.Close() + groupIDs := make([]string, 0) + for rows.Next() { + var groupID int64 + if err := rows.Scan(&groupID); err != nil { + return nil, fmt.Errorf("scan product group id: %w", err) + } + groupIDs = append(groupIDs, formatID(groupID)) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate product group ids: %w", err) + } + return groupIDs, nil +} + +func (r *ProductRepository) listProductCategoryIDs(ctx context.Context, productID string, scope StoreScope) ([]string, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + parsedProductID, err := parseID(productID, "product_id") + if err != nil { + return nil, err + } + rows, err := r.db.QueryContext(ctx, ` +SELECT c.id +FROM product.product_category_bindings AS b +JOIN product.product_category AS c ON c.id = b.product_category_id +WHERE b.product_id = $1 + AND b.tenant_id = $2 + AND b.store_id = $3 + AND b.deleted_at IS NULL + AND c.deleted_at IS NULL +ORDER BY c.level, c.priority, c.id +`, parsedProductID, scope.TenantID, scope.StoreID) + if err != nil { + return nil, fmt.Errorf("list product category ids: %w", err) + } + defer rows.Close() + categoryIDs := make([]string, 0) + for rows.Next() { + var categoryID int64 + if err := rows.Scan(&categoryID); err != nil { + return nil, fmt.Errorf("scan product category id: %w", err) + } + categoryIDs = append(categoryIDs, formatID(categoryID)) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate product category ids: %w", err) + } + return categoryIDs, nil +} + // BatchGetCartItemProducts loads current catalog facts for cart lines in request order. // It includes archived SKUs, but treats soft-deleted SPUs and SKUs as unavailable. -func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup) ([]CartItemProductRecord, error) { +func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookups []CartItemProductLookup, scope StoreScope) ([]CartItemProductRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } if len(lookups) == 0 { return []CartItemProductRecord{}, nil } @@ -1941,7 +3414,7 @@ func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookup } } - products, err := r.loadProductsByIDs(ctx, productIDs) + products, err := r.loadProductsByIDs(ctx, productIDs, scope) if err != nil { return nil, err } @@ -1973,8 +3446,117 @@ func (r *ProductRepository) BatchGetCartItemProducts(ctx context.Context, lookup return results, nil } +// BatchGetStorefrontProductSKUs returns only sellable SKU prices for visible +// storefront products. Archived, disabled and soft-deleted specifications are +// intentionally absent so promotion displays cannot advertise an unavailable SKU. +func (r *ProductRepository) BatchGetStorefrontProductSKUs(ctx context.Context, productIDs []string, scope StoreScope) ([]StorefrontProductSKURecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + if len(productIDs) == 0 { + return []StorefrontProductSKURecord{}, nil + } + + placeholders := make([]string, 0, len(productIDs)) + args := make([]any, 0, len(productIDs)+3) + seen := make(map[string]struct{}, len(productIDs)) + for _, productID := range productIDs { + if _, exists := seen[productID]; exists { + continue + } + parsedID, err := parseID(productID, "product id") + if err != nil { + return nil, err + } + seen[productID] = struct{}{} + args = append(args, parsedID) + placeholders = append(placeholders, fmt.Sprintf("$%d", len(args))) + } + args = append(args, scope.StoreID, + statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), + statusToDB(productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT), + ) + storeArg := len(args) - 2 + onSaleArg := len(args) - 1 + offSaleArg := len(args) + + rows, err := r.db.QueryContext(ctx, fmt.Sprintf(` +SELECT pi.product_id, pi.id, pi.price +FROM product.product_items pi +JOIN product.products p ON p.id = pi.product_id +WHERE pi.product_id IN (%s) + AND p.deleted_at IS NULL + AND p.store_id = $%d + AND p.status IN ($%d, $%d) + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 +ORDER BY pi.product_id ASC, pi.price ASC, pi.id ASC +`, strings.Join(placeholders, ", "), storeArg, onSaleArg, offSaleArg), args...) + if err != nil { + return nil, fmt.Errorf("query storefront product skus: %w", err) + } + defer rows.Close() + + result := make([]StorefrontProductSKURecord, 0) + for rows.Next() { + var productID, skuID int64 + var price int64 + if err := rows.Scan(&productID, &skuID, &price); err != nil { + return nil, fmt.Errorf("scan storefront product sku: %w", err) + } + result = append(result, StorefrontProductSKURecord{ + ProductID: formatID(productID), + SKUID: formatID(skuID), + Price: price, + }) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate storefront product skus: %w", err) + } + return result, nil +} + +// ValidateProductGroup verifies that a leaf group belongs to the current store. +func (r *ProductRepository) ValidateProductGroup(ctx context.Context, groupID string, scope StoreScope) error { + if err := requireWriteScope(scope); err != nil { + return err + } + parsedGroupID, err := parseID(groupID, "group_id") + if err != nil { + return err + } + var found int64 + err = r.db.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(&found) + if errors.Is(err, sql.ErrNoRows) { + return ErrInvalidProductGroup + } + if err != nil { + return fmt.Errorf("validate product group: %w", err) + } + return nil +} + // ListProducts loads paginated summaries for all non-deleted products. -func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { +func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int32, filter ProductListFilter, scope StoreScope) ([]*CategoryProductRecord, int64, error) { + if err := requireWriteScope(scope); err != nil { + return nil, 0, err + } if page < 1 { page = 1 } @@ -1982,32 +3564,8 @@ func (r *ProductRepository) ListProducts(ctx context.Context, page, pageSize int pageSize = 20 } - var total int64 - if err := r.db.QueryRowContext(ctx, ` -SELECT COUNT(*) -FROM product.products -WHERE deleted_at IS NULL -`).Scan(&total); err != nil { - return nil, 0, fmt.Errorf("count products: %w", err) - } - if total == 0 { - return []*CategoryProductRecord{}, 0, nil - } - - offset := int64(page-1) * int64(pageSize) - rows, err := r.db.QueryContext(ctx, ` -SELECT p.updated_at, - p.created_at, - p.title, - p.id, - p.spu_no, - p.status, - COALESCE(to_json(p.image_ids)::text, '[]'), - COALESCE(sku_summary.price, 0), - COALESCE(sku_summary.sold_quantity, 0), - COALESCE(sku_summary.stock_quantity, 0), - COALESCE(sku_summary.locked_quantity, 0) -FROM product.products p + where, args := productListWhere(filter, scope) + metricJoin := ` LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, @@ -2018,11 +3576,40 @@ LEFT JOIN LATERAL ( WHERE pi.product_id = p.id AND pi.deleted_at IS NULL AND pi.is_archived = FALSE -) sku_summary ON TRUE -WHERE p.deleted_at IS NULL +) sku_summary ON TRUE` + + var total int64 + countQuery := "SELECT COUNT(*) FROM product.products p " + metricJoin + " WHERE " + where + if err := r.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil { + return nil, 0, fmt.Errorf("count products: %w", err) + } + if total == 0 { + return []*CategoryProductRecord{}, 0, nil + } + + offset := int64(page-1) * int64(pageSize) + queryArgs := append(append([]any{}, args...), pageSize, offset) + limitArg := len(args) + 1 + offsetArg := len(args) + 2 + rows, err := r.db.QueryContext(ctx, ` +SELECT p.updated_at, + p.created_at, + p.title, + p.id, + p.spu_no, + p.status, + COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(p.category_properties, '{}'::jsonb)::text, + p.is_distribution_product, + p.presale_type, + COALESCE(sku_summary.price, 0), + COALESCE(sku_summary.sold_quantity, 0), + COALESCE(sku_summary.stock_quantity, 0), + COALESCE(sku_summary.locked_quantity, 0) +FROM product.products p `+metricJoin+` +WHERE `+where+` ORDER BY p.created_at DESC, p.id DESC -LIMIT $1 OFFSET $2 -`, pageSize, offset) +LIMIT $`+strconv.Itoa(limitArg)+` OFFSET $`+strconv.Itoa(offsetArg), queryArgs...) if err != nil { return nil, 0, fmt.Errorf("query products: %w", err) } @@ -2039,13 +3626,327 @@ LIMIT $1 OFFSET $2 if err := rows.Err(); err != nil { return nil, 0, fmt.Errorf("iterate products: %w", err) } + if err := r.populateProductListMetadata(ctx, products, scope); err != nil { + return nil, 0, err + } return products, total, nil } +// populateProductListMetadata loads list-only display projections in batches so +// product pagination never causes one query per product. +func (r *ProductRepository) populateProductListMetadata(ctx context.Context, products []*CategoryProductRecord, scope StoreScope) error { + if len(products) == 0 { + return nil + } + productIDs := make([]int64, 0, len(products)) + byID := make(map[string]*CategoryProductRecord, len(products)) + for _, product := range products { + if product == nil { + continue + } + id, err := parseID(product.ID, "product_id") + if err != nil { + return err + } + productIDs = append(productIDs, id) + byID[product.ID] = product + product.ProductCategories = []ProductCategorySummaryRecord{} + product.Groups = []ProductGroupSummaryRecord{} + } + if len(productIDs) == 0 { + return nil + } + if err := r.populateProductCategorySummaries(ctx, productIDs, byID, scope); err != nil { + return err + } + if err := r.populateProductGroupSummaries(ctx, productIDs, byID, scope); err != nil { + return err + } + if err := r.populateProductBrandSummaries(ctx, productIDs, byID, scope); err != nil { + return err + } + return nil +} + +func nullableFormattedID(value sql.NullInt64) *string { + if !value.Valid { + return nil + } + id := formatID(value.Int64) + return &id +} + +func (r *ProductRepository) populateProductCategorySummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error { + summaries, err := r.loadProductCategorySummaries(ctx, productIDs, scope) + if err != nil { + return err + } + for productID, product := range products { + if product != nil { + product.ProductCategories = append(product.ProductCategories, summaries[productID]...) + } + } + return nil +} + +// loadProductCategorySummaries returns every direct standard-category binding +// for the supplied products together with its complete active ancestor path. +// It is shared by product lists and the product-detail read path. +func (r *ProductRepository) loadProductCategorySummaries(ctx context.Context, productIDs []int64, scope StoreScope) (map[string][]ProductCategorySummaryRecord, error) { + result := make(map[string][]ProductCategorySummaryRecord, len(productIDs)) + if len(productIDs) == 0 { + return result, nil + } + placeholders, idArgs := productIDPlaceholders(productIDs, 3) + args := append([]any{scope.TenantID, scope.StoreID}, idArgs...) + rows, err := r.db.QueryContext(ctx, ` +WITH RECURSIVE category_paths AS ( + SELECT b.product_id, + c.id AS bound_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_bindings b + JOIN product.product_category c ON c.id = b.product_category_id + WHERE b.tenant_id = $1 + AND b.store_id = $2 + AND b.deleted_at IS NULL + AND c.deleted_at IS NULL + AND b.product_id IN (`+placeholders+`) + UNION ALL + SELECT cp.product_id, + cp.bound_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 product_id, bound_category_id, id, parent_id, name, level, depth +FROM category_paths +ORDER BY product_id, bound_category_id, depth DESC`, args...) + if err != nil { + return nil, fmt.Errorf("list product category summaries: %w", err) + } + defer rows.Close() + + byProductCategory := make(map[string]map[string]*ProductCategorySummaryRecord) + for rows.Next() { + var productID, boundCategoryID, categoryID int64 + var parentID sql.NullInt64 + var name string + var level, depth int32 + if err := rows.Scan(&productID, &boundCategoryID, &categoryID, &parentID, &name, &level, &depth); err != nil { + return nil, fmt.Errorf("scan product category summary: %w", err) + } + productKey, boundKey := formatID(productID), formatID(boundCategoryID) + categoryByProduct := byProductCategory[productKey] + if categoryByProduct == nil { + categoryByProduct = make(map[string]*ProductCategorySummaryRecord) + byProductCategory[productKey] = categoryByProduct + } + summary := categoryByProduct[boundKey] + if summary == nil { + summary = &ProductCategorySummaryRecord{ID: boundKey, Path: []ProductCategoryPathNodeRecord{}} + categoryByProduct[boundKey] = summary + } + if depth == 0 { + summary.Name = name + summary.Level = level + summary.ParentID = nullableFormattedID(parentID) + } + summary.Path = append(summary.Path, ProductCategoryPathNodeRecord{ + ID: formatID(categoryID), Name: name, Level: level, ParentID: nullableFormattedID(parentID), + }) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate product category summaries: %w", err) + } + for productID, categories := range byProductCategory { + productCategories := make([]ProductCategorySummaryRecord, 0, len(categories)) + for _, category := range categories { + if category.ParentID != nil { + for _, node := range category.Path { + if node.ID == *category.ParentID { + category.ParentName = node.Name + break + } + } + } + productCategories = append(productCategories, *category) + } + sort.Slice(productCategories, func(i, j int) bool { + left, right := productCategories[i], productCategories[j] + if left.Level != right.Level { + return left.Level < right.Level + } + return left.ID < right.ID + }) + result[productID] = productCategories + } + return result, nil +} + +func (r *ProductRepository) populateProductGroupSummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error { + placeholders, idArgs := productIDPlaceholders(productIDs, 2) + args := append([]any{scope.StoreID}, idArgs...) + rows, err := r.db.QueryContext(ctx, ` +SELECT b.product_id, c.id, c.name +FROM product.product_catalog_bindings b +JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL +WHERE c.store_id = $1 + AND c.node_type = 2 + AND b.deleted_at IS NULL + AND b.product_id IN (`+placeholders+`) +ORDER BY b.product_id, c.sort_num, c.id`, args...) + if err != nil { + return fmt.Errorf("list product group summaries: %w", err) + } + defer rows.Close() + for rows.Next() { + var productID, groupID int64 + var name string + if err := rows.Scan(&productID, &groupID, &name); err != nil { + return fmt.Errorf("scan product group summary: %w", err) + } + if product := products[formatID(productID)]; product != nil { + product.Groups = append(product.Groups, ProductGroupSummaryRecord{ID: formatID(groupID), Name: name}) + } + } + if err := rows.Err(); err != nil { + return fmt.Errorf("iterate product group summaries: %w", err) + } + return nil +} + +func (r *ProductRepository) populateProductBrandSummaries(ctx context.Context, productIDs []int64, products map[string]*CategoryProductRecord, scope StoreScope) error { + placeholders, idArgs := productIDPlaceholders(productIDs, 3) + args := append([]any{scope.TenantID, scope.StoreID}, idArgs...) + rows, err := r.db.QueryContext(ctx, ` +SELECT p.id, b.id, b.name, b.alias, b.brand_code +FROM product.products p +JOIN product.brands b ON b.id = p.brand_id + AND b.tenant_id = $1 + AND b.store_id = $2 + AND b.deleted_at IS NULL +WHERE p.id IN (`+placeholders+`) + AND p.tenant_id = $1 + AND p.store_id = $2 + AND p.deleted_at IS NULL`, args...) + if err != nil { + return fmt.Errorf("list product brand summaries: %w", err) + } + defer rows.Close() + for rows.Next() { + var productID, brandID int64 + var name, alias, brandCode string + if err := rows.Scan(&productID, &brandID, &name, &alias, &brandCode); err != nil { + return fmt.Errorf("scan product brand summary: %w", err) + } + if product := products[formatID(productID)]; product != nil { + product.Brand = &ProductBrandSummaryRecord{ID: formatID(brandID), Name: name, Alias: alias, BrandCode: brandCode} + } + } + if err := rows.Err(); err != nil { + return fmt.Errorf("iterate product brand summaries: %w", err) + } + return nil +} + +func productListWhere(filter ProductListFilter, scope StoreScope) (string, []any) { + predicates := []string{"p.deleted_at IS NULL", "p.store_id = $1"} + args := []any{scope.StoreID} + add := func(predicate string, value any) { + args = append(args, value) + predicates = append(predicates, fmt.Sprintf(predicate, len(args))) + } + if filter.CreatedAtFrom != nil { + add("p.created_at >= $%d", *filter.CreatedAtFrom) + } + if filter.CreatedAtTo != nil { + add("p.created_at <= $%d", *filter.CreatedAtTo) + } + if filter.TitleKeyword != "" { + add(`p.title ILIKE $%d ESCAPE '\'`, "%"+escapeLikeLiteral(filter.TitleKeyword)+"%") + } + if filter.SPUNo != "" { + add("p.spu_no = $%d", filter.SPUNo) + } + if filter.GroupID != "" { + add(`EXISTS ( + SELECT 1 + FROM product.product_catalog_bindings pcb + JOIN product.catalog_category pc ON pc.id = pcb.category_id AND pc.deleted_at IS NULL + WHERE pcb.product_id = p.id + AND pcb.category_id = $%d + AND pcb.deleted_at IS NULL + AND pc.node_type = 2 + AND pc.store_id = p.store_id +)`, filter.GroupID) + } + if filter.ProductCategoryID != "" { + args = append(args, filter.ProductCategoryID) + argPos := len(args) + predicates = append(predicates, fmt.Sprintf(`EXISTS ( + WITH RECURSIVE category_descendants AS ( + SELECT c.id + FROM product.product_category c + WHERE c.id = $%d + AND c.deleted_at IS NULL + UNION + SELECT child.id + FROM product.product_category child + JOIN category_descendants parent ON child.parent_id = parent.id + WHERE child.deleted_at IS NULL + ) + SELECT 1 + FROM product.product_category_bindings pcb + JOIN category_descendants descendant ON descendant.id = pcb.product_category_id + WHERE pcb.product_id = p.id + AND pcb.tenant_id = p.tenant_id + AND pcb.store_id = p.store_id + AND pcb.deleted_at IS NULL +)`, argPos)) + } + if filter.GoodsType != nil { + add("p.goods_type = $%d", *filter.GoodsType) + } + if filter.SoldQuantityMin != nil { + add("COALESCE(sku_summary.sold_quantity, 0) >= $%d", *filter.SoldQuantityMin) + } + if filter.SoldQuantityMax != nil { + add("COALESCE(sku_summary.sold_quantity, 0) <= $%d", *filter.SoldQuantityMax) + } + if filter.PriceMin != nil { + add("COALESCE(sku_summary.price, 0) >= $%d", *filter.PriceMin) + } + if filter.PriceMax != nil { + add("COALESCE(sku_summary.price, 0) <= $%d", *filter.PriceMax) + } + if filter.PresaleType != nil { + add("p.presale_type = $%d", *filter.PresaleType) + } + if filter.Status != nil { + add("p.status = $%d", statusToDB(*filter.Status)) + } + return strings.Join(predicates, " AND "), args +} + // SearchProducts loads storefront-visible product summaries whose titles contain // keyword. Callers cannot opt out of the visibility predicate: soft-deleted and // inventory-only products must never be exposed by keyword search. -func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32) ([]*CategoryProductRecord, int64, error) { +func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, page, pageSize int32, scope StoreScope) ([]*CategoryProductRecord, int64, error) { + if err := requireWriteScope(scope); err != nil { + return nil, 0, err + } if page < 1 { page = 1 } @@ -2057,16 +3958,25 @@ func (r *ProductRepository) SearchProducts(ctx context.Context, keyword string, containsPattern := "%" + escapedKeyword + "%" prefixPattern := escapedKeyword + "%" onSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE) - offSaleStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE) + soldOutStatus := statusToDB(productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT) var total int64 if err := r.db.QueryRowContext(ctx, ` -SELECT COUNT(*) +SELECT COUNT(DISTINCT p.id) FROM product.products p WHERE p.deleted_at IS NULL + AND p.store_id = $4 AND p.status IN ($2, $3) + AND EXISTS ( + SELECT 1 + FROM product.product_items pi + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + ) AND p.title ILIKE $1 ESCAPE '\' -`, containsPattern, onSaleStatus, offSaleStatus).Scan(&total); err != nil { +`, containsPattern, onSaleStatus, soldOutStatus, scope.StoreID).Scan(&total); err != nil { return nil, 0, fmt.Errorf("count searched products: %w", err) } if total == 0 { @@ -2081,7 +3991,10 @@ SELECT p.updated_at, p.id, p.spu_no, p.status, - COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(p.category_properties, '{}'::jsonb)::text, + p.is_distribution_product, + p.presale_type, COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.stock_quantity, 0), @@ -2097,9 +4010,19 @@ LEFT JOIN LATERAL ( WHERE pi.product_id = p.id AND pi.deleted_at IS NULL AND pi.is_archived = FALSE + AND pi.status = 1 ) sku_summary ON TRUE WHERE p.deleted_at IS NULL + AND p.store_id = $8 AND p.status IN ($2, $3) + AND EXISTS ( + SELECT 1 + FROM product.product_items pi + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + ) AND p.title ILIKE $1 ESCAPE '\' ORDER BY CASE WHEN LOWER(p.title) = LOWER($4) THEN 0 @@ -2109,7 +4032,7 @@ ORDER BY CASE p.updated_at DESC, p.id DESC LIMIT $6 OFFSET $7 -`, containsPattern, onSaleStatus, offSaleStatus, keyword, prefixPattern, pageSize, offset) +`, containsPattern, onSaleStatus, soldOutStatus, keyword, prefixPattern, pageSize, offset, scope.StoreID) if err != nil { return nil, 0, fmt.Errorf("query searched products: %w", err) } @@ -2130,7 +4053,10 @@ LIMIT $6 OFFSET $7 } // CountProducts returns aggregate product counts grouped by lifecycle status. -func (r *ProductRepository) CountProducts(ctx context.Context) (*ProductCountRecord, error) { +func (r *ProductRepository) CountProducts(ctx context.Context, scope StoreScope) (*ProductCountRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } var counts ProductCountRecord if err := r.db.QueryRowContext(ctx, ` SELECT COUNT(*) AS total, @@ -2140,7 +4066,8 @@ SELECT COUNT(*) AS total, COUNT(*) FILTER (WHERE deleted_at IS NULL AND status = 3) AS off_sale, COUNT(*) FILTER (WHERE deleted_at IS NOT NULL) AS deleted FROM product.products -`).Scan( +WHERE store_id = $1 +`, scope.StoreID).Scan( &counts.Total, &counts.Active, &counts.Draft, @@ -2153,11 +4080,14 @@ FROM product.products return &counts, nil } -// ListCategoryProducts loads paginated product summaries for a category ID. -func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool) ([]*CategoryProductRecord, int64, error) { +// ListCategoryProducts loads paginated product summaries for a category or group node. +func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID string, page, pageSize int32, onlyVisible bool, targetNodeType int32, scope StoreScope) ([]*CategoryProductRecord, []string, int64, error) { + if err := requireWriteScope(scope); err != nil { + return nil, nil, 0, err + } parsedCategoryID, err := parseID(categoryID, "category id") if err != nil { - return nil, 0, err + return nil, nil, 0, err } if page < 1 { @@ -2166,37 +4096,116 @@ func (r *ProductRepository) ListCategoryProducts(ctx context.Context, categoryID if pageSize < 1 { pageSize = 20 } + if onlyVisible && targetNodeType == 1 { + visible, err := r.isStorefrontCategoryVisible(ctx, parsedCategoryID, scope) + if err != nil { + return nil, nil, 0, err + } + if !visible { + return nil, nil, 0, ErrStorefrontCategoryNotFound + } + } var total int64 if err := r.db.QueryRowContext(ctx, ` SELECT COUNT(*) FROM product.products p -JOIN product.product_category_bindings b ON b.product_id = p.id -WHERE b.category_id = $1 +JOIN product.product_catalog_bindings b ON b.product_id = p.id +JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL +WHERE (($6 = 2 AND b.category_id = $1) OR ($6 = 1 AND b.category_id IN ( + WITH RECURSIVE descendants(id) AS ( + SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1 AND deleted_at IS NULL + UNION ALL + SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id + WHERE child.store_id = $5 AND child.node_type = 1 AND child.deleted_at IS NULL + ) SELECT id FROM descendants + ))) AND p.deleted_at IS NULL + AND b.deleted_at IS NULL + AND p.store_id = $5 + AND c.store_id = $5 + AND c.node_type = $6 AND ($2 = FALSE OR p.status IN ($3, $4)) -`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE)).Scan(&total); err != nil { - return nil, 0, fmt.Errorf("count category products: %w", err) + AND ($2 = FALSE OR EXISTS ( + SELECT 1 + FROM product.product_items pi + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + )) +`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT), scope.StoreID, targetNodeType).Scan(&total); err != nil { + return nil, nil, 0, fmt.Errorf("count category products: %w", err) } if total == 0 { - return []*CategoryProductRecord{}, 0, nil + return []*CategoryProductRecord{}, []string{}, 0, nil + } + + idRows, err := r.db.QueryContext(ctx, ` +SELECT p.id +FROM product.products p +JOIN product.product_catalog_bindings b ON b.product_id = p.id +JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL +WHERE (($6 = 2 AND b.category_id = $1) OR ($6 = 1 AND b.category_id IN ( + WITH RECURSIVE descendants(id) AS ( + SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $5 AND node_type = 1 AND deleted_at IS NULL + UNION ALL + SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id + WHERE child.store_id = $5 AND child.node_type = 1 AND child.deleted_at IS NULL + ) SELECT id FROM descendants + ))) + AND p.deleted_at IS NULL + AND b.deleted_at IS NULL + AND p.store_id = $5 + AND c.store_id = $5 + AND c.node_type = $6 + AND ($2 = FALSE OR p.status IN ($3, $4)) + AND ($2 = FALSE OR EXISTS ( + SELECT 1 + FROM product.product_items pi + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + )) +GROUP BY p.id +ORDER BY MAX(p.created_at) DESC, p.id DESC +`, parsedCategoryID, onlyVisible, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT), scope.StoreID, targetNodeType) + if err != nil { + return nil, nil, 0, fmt.Errorf("query category product ids: %w", err) + } + defer idRows.Close() + productIDs := make([]string, 0) + for idRows.Next() { + var productID int64 + if err := idRows.Scan(&productID); err != nil { + return nil, nil, 0, fmt.Errorf("scan category product id: %w", err) + } + productIDs = append(productIDs, formatID(productID)) + } + if err := idRows.Err(); err != nil { + return nil, nil, 0, fmt.Errorf("iterate category product ids: %w", err) } offset := int64(page-1) * int64(pageSize) rows, err := r.db.QueryContext(ctx, ` -SELECT p.updated_at, +SELECT DISTINCT p.updated_at, p.created_at, p.title, p.id, p.spu_no, p.status, - COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(to_json(p.image_ids)::text, '[]'), + COALESCE(p.category_properties, '{}'::jsonb)::text, + p.is_distribution_product, + p.presale_type, COALESCE(sku_summary.price, 0), COALESCE(sku_summary.sold_quantity, 0), COALESCE(sku_summary.stock_quantity, 0), COALESCE(sku_summary.locked_quantity, 0) FROM product.products p -JOIN product.product_category_bindings b ON b.product_id = p.id +JOIN product.product_catalog_bindings b ON b.product_id = p.id +JOIN product.catalog_category c ON c.id = b.category_id AND c.deleted_at IS NULL LEFT JOIN LATERAL ( SELECT MIN(pi.price) AS price, SUM(COALESCE(inv.sold_quantity, 0)) AS sold_quantity, @@ -2207,15 +4216,35 @@ LEFT JOIN LATERAL ( WHERE pi.product_id = p.id AND pi.deleted_at IS NULL AND pi.is_archived = FALSE + AND ($2 = FALSE OR pi.status = 1) ) sku_summary ON TRUE -WHERE b.category_id = $1 +WHERE (($8 = 2 AND b.category_id = $1) OR ($8 = 1 AND b.category_id IN ( + WITH RECURSIVE descendants(id) AS ( + SELECT id FROM product.catalog_category WHERE id = $1 AND store_id = $7 AND node_type = 1 AND deleted_at IS NULL + UNION ALL + SELECT child.id FROM product.catalog_category child JOIN descendants parent ON child.parent_id = parent.id + WHERE child.store_id = $7 AND child.node_type = 1 AND child.deleted_at IS NULL + ) SELECT id FROM descendants + ))) AND p.deleted_at IS NULL + AND b.deleted_at IS NULL + AND p.store_id = $7 + AND c.store_id = $7 + AND c.node_type = $8 AND ($2 = FALSE OR p.status IN ($5, $6)) + AND ($2 = FALSE OR EXISTS ( + SELECT 1 + FROM product.product_items pi + WHERE pi.product_id = p.id + AND pi.deleted_at IS NULL + AND pi.is_archived = FALSE + AND pi.status = 1 + )) ORDER BY p.created_at DESC, p.id DESC LIMIT $3 OFFSET $4 -`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE)) +`, parsedCategoryID, onlyVisible, pageSize, offset, statusToDB(productv1.ProductStatus_PRODUCT_STATUS_ON_SALE), statusToDB(productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT), scope.StoreID, targetNodeType) if err != nil { - return nil, 0, fmt.Errorf("query category products: %w", err) + return nil, nil, 0, fmt.Errorf("query category products: %w", err) } defer rows.Close() @@ -2223,18 +4252,86 @@ LIMIT $3 OFFSET $4 for rows.Next() { product, err := scanCategoryProduct(rows) if err != nil { - return nil, 0, err + return nil, nil, 0, err } products = append(products, product) } if err := rows.Err(); err != nil { - return nil, 0, fmt.Errorf("iterate category products: %w", err) + return nil, nil, 0, fmt.Errorf("iterate category products: %w", err) } - return products, total, nil + return products, productIDs, total, nil } -// ListCategoryTreeNodes loads product category nodes for storefront category trees. -func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { +// isStorefrontCategoryVisible verifies the requested category and every +// ancestor in one store. A broken parent link or cycle is not storefront +// visible: exposing it would either leak a hidden branch or promote a child to +// a false root in the miniapp category tree. +func (r *ProductRepository) isStorefrontCategoryVisible(ctx context.Context, categoryID int64, scope StoreScope) (bool, error) { + var visible bool + err := r.db.QueryRowContext(ctx, ` +WITH RECURSIVE ancestry AS ( + SELECT id, parent_id, status, ARRAY[id] AS path + FROM product.catalog_category + WHERE id = $1 + AND store_id = $2 + AND node_type = 1 + AND deleted_at IS NULL + + UNION ALL + + SELECT parent.id, parent.parent_id, parent.status, ancestry.path || parent.id + FROM product.catalog_category parent + JOIN ancestry ON ancestry.parent_id = parent.id + WHERE parent.store_id = $2 + AND parent.node_type = 1 + AND parent.deleted_at IS NULL + AND NOT parent.id = ANY(ancestry.path) +) +SELECT EXISTS (SELECT 1 FROM ancestry WHERE parent_id IS NULL) + AND NOT EXISTS (SELECT 1 FROM ancestry WHERE status <> 1) + AND NOT EXISTS ( + SELECT 1 + FROM ancestry child + WHERE child.parent_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 + FROM product.catalog_category parent + WHERE parent.id = child.parent_id + AND parent.store_id = $2 + AND parent.node_type = 1 + AND parent.deleted_at IS NULL + ) + ) +`, categoryID, scope.StoreID).Scan(&visible) + if err != nil { + return false, fmt.Errorf("check storefront category visibility: %w", err) + } + return visible, nil +} + +// ListCategoryTreeNodes loads a complete catalog tree (maxDepth=0) or a +// lazily-loaded slice beginning at rootID. maxDepth counts edges below a root. +func (r *ProductRepository) ListCategoryTreeNodes(ctx context.Context, onlyVisible bool, rootID string, maxDepth int32, scope StoreScope) ([]*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } + var root any + if strings.TrimSpace(rootID) != "" { + parsed, err := parseID(rootID, "category_id") + if err != nil { + return nil, err + } + if onlyVisible { + visible, err := r.isStorefrontCategoryVisible(ctx, parsed, scope) + if err != nil { + return nil, err + } + if !visible { + return nil, ErrStorefrontCategoryNotFound + } + } + root = parsed + } rows, err := r.db.QueryContext(ctx, ` SELECT id, node_type, @@ -2244,12 +4341,34 @@ SELECT id, COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, + campaign_id, version -FROM product.product_category -WHERE node_type = 1 - AND ($1 = false OR status = 1) +FROM ( + WITH RECURSIVE category_tree AS ( + SELECT id, node_type, name, parent_id, level, image_ids, sort_num, status, campaign_id, version, 0 AS depth, ARRAY[id] AS path + FROM product.catalog_category + WHERE node_type = 1 + AND store_id = $2 + AND deleted_at IS NULL + AND (($3::BIGINT IS NULL AND parent_id IS NULL) OR id = $3) + AND ($1 = FALSE OR status = 1) + + UNION ALL + + SELECT child.id, child.node_type, child.name, child.parent_id, child.level, child.image_ids, child.sort_num, child.status, child.campaign_id, child.version, parent.depth + 1, parent.path || child.id + FROM product.catalog_category child + JOIN category_tree parent ON child.parent_id = parent.id + WHERE child.node_type = 1 + AND child.store_id = $2 + AND child.deleted_at IS NULL + AND ($1 = FALSE OR child.status = 1) + AND ($4 = 0 OR parent.depth < $4) + AND NOT child.id = ANY(parent.path) + ) + SELECT * FROM category_tree +) category_tree ORDER BY level ASC, sort_num ASC, id ASC -`, onlyVisible) +`, onlyVisible, scope.StoreID, root, maxDepth) if err != nil { return nil, fmt.Errorf("query category tree nodes: %w", err) } @@ -2270,55 +4389,250 @@ ORDER BY level ASC, sort_num ASC, id ASC return categories, nil } -// ListGroupNodes loads product group nodes. -func (r *ProductRepository) ListGroupNodes(ctx context.Context, onlyVisible bool) ([]*CategoryRecord, error) { - rows, err := r.db.QueryContext(ctx, ` -SELECT id, - node_type, - name, - parent_id, - level, - COALESCE(to_json(image_ids)::text, '[]'), - sort_num, - status, - version -FROM product.product_category -WHERE node_type = 2 - AND ($1 = false OR status = 1) -ORDER BY sort_num ASC, id ASC -`, onlyVisible) +// GroupListQueryError retains the executed statement for server-side diagnostics. +type GroupListQueryError struct { + Query string + Args []any + Err error +} + +func (e *GroupListQueryError) Error() string { return fmt.Sprintf("query group nodes: %v", e.Err) } +func (e *GroupListQueryError) Unwrap() error { return e.Err } + +// ListGroupNodes loads one page of product group nodes and their leaf-brand bindings. +func (r *ProductRepository) ListGroupNodes(ctx context.Context, filter GroupListFilter, page, pageSize int32, scope StoreScope) ([]*CategoryRecord, int64, error) { + if err := requireWriteScope(scope); err != nil { + return nil, 0, err + } + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + firstLevelName := strings.TrimSpace(filter.FirstLevelName) + secondLevelName := strings.TrimSpace(filter.SecondLevelName) + if !filter.ExactMatch { + firstLevelName = escapeLikeLiteral(firstLevelName) + secondLevelName = escapeLikeLiteral(secondLevelName) + } + var total int64 + if err := r.db.QueryRowContext(ctx, ` +SELECT COUNT(*) +FROM product.catalog_category AS c +LEFT JOIN product.catalog_category AS parent ON parent.id = c.parent_id + AND parent.store_id = c.store_id + AND parent.node_type = 2 + AND parent.deleted_at IS NULL +WHERE c.node_type = 2 + AND c.store_id = $1 + AND c.deleted_at IS NULL + AND ($2 = false OR c.status = 1) + AND ($3 = '' OR CASE + WHEN $5 THEN LOWER(CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END) = LOWER($3) + ELSE CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END ILIKE ('%' || $3 || '%') ESCAPE '\' + END) + AND ($4 = '' OR (c.level = 2 AND CASE + WHEN $5 THEN LOWER(c.name) = LOWER($4) + ELSE c.name ILIKE ('%' || $4 || '%') ESCAPE '\' + END)) +`, scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch).Scan(&total); err != nil { + return nil, 0, fmt.Errorf("count group nodes: %w", err) + } + if total == 0 { + return []*CategoryRecord{}, 0, nil + } + + offset := int64(page-1) * int64(pageSize) + const query = ` +SELECT c.id, + c.node_type, + c.name, + c.parent_id, + c.level, + COALESCE(to_json(c.image_ids)::text, '[]'), + c.sort_num, + c.status, + c.campaign_id, + c.version, + COUNT(p.id) AS product_count, + NOT EXISTS ( + SELECT 1 + FROM product.catalog_category child + WHERE child.parent_id = c.id + AND child.store_id = c.store_id + AND child.node_type = 2 + AND child.deleted_at IS NULL + ) AS is_leaf +FROM product.catalog_category AS c +LEFT JOIN product.catalog_category AS parent ON parent.id = c.parent_id + AND parent.store_id = c.store_id + AND parent.node_type = 2 + AND parent.deleted_at IS NULL +LEFT JOIN product.product_catalog_bindings AS b ON b.category_id = c.id AND b.deleted_at IS NULL +LEFT JOIN product.products AS p ON p.id = b.product_id + AND p.store_id = c.store_id + AND p.deleted_at IS NULL +WHERE c.node_type = 2 + AND c.store_id = $1 + AND c.deleted_at IS NULL + AND ($2 = false OR c.status = 1) + AND ($3 = '' OR CASE + WHEN $5 THEN LOWER(CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END) = LOWER($3) + ELSE CASE WHEN c.level = 1 THEN c.name ELSE COALESCE(parent.name, '') END ILIKE ('%' || $3 || '%') ESCAPE '\' + END) + AND ($4 = '' OR (c.level = 2 AND CASE + WHEN $5 THEN LOWER(c.name) = LOWER($4) + ELSE c.name ILIKE ('%' || $4 || '%') ESCAPE '\' + END)) +GROUP BY c.id +ORDER BY c.created_at DESC, c.id DESC +LIMIT $6 OFFSET $7 +` + args := []any{scope.StoreID, filter.OnlyVisible, firstLevelName, secondLevelName, filter.ExactMatch, pageSize, offset} + rows, err := r.db.QueryContext(ctx, query, args...) if err != nil { - return nil, fmt.Errorf("query group nodes: %w", err) + return nil, 0, &GroupListQueryError{Query: query, Args: args, Err: err} } defer rows.Close() groups := make([]*CategoryRecord, 0) for rows.Next() { - group, err := scanCategory(rows) + group, err := scanGroup(rows) if err != nil { - return nil, err + return nil, 0, err } groups = append(groups, group) } if err := rows.Err(); err != nil { - return nil, fmt.Errorf("iterate group nodes: %w", err) + return nil, 0, fmt.Errorf("iterate group nodes: %w", err) + } + if err := r.populateGroupBrandProducts(ctx, groups, scope); err != nil { + return nil, 0, err } - return groups, nil + return groups, total, nil } -func (r *ProductRepository) loadProductByID(ctx context.Context, productID string) (*ProductRecord, error) { - products, err := r.loadProductsByIDs(ctx, []string{productID}) +func (r *ProductRepository) populateGroupBrandProducts(ctx context.Context, groups []*CategoryRecord, scope StoreScope) error { + leafIDs := make([]int64, 0, len(groups)) + groupsByID := make(map[string]*CategoryRecord, len(groups)) + for _, group := range groups { + if !group.IsLeaf { + continue + } + id, err := parseID(group.ID, "group_id") + if err != nil { + return err + } + leafIDs = append(leafIDs, id) + groupsByID[group.ID] = group + } + if len(leafIDs) == 0 { + return nil + } + + placeholders, idArgs := productIDPlaceholders(leafIDs, 3) + args := append([]any{scope.TenantID, scope.StoreID}, idArgs...) + rows, err := r.db.QueryContext(ctx, ` +SELECT c.id, + COALESCE(p.brand_id, 0) AS brand_id, + CASE + WHEN p.brand_id IS NULL THEN '未设置品牌' + WHEN b.id IS NULL THEN '品牌已删除' + ELSE b.name + END AS brand_name, + p.id, + COALESCE(p.spu_no, '') AS spu_no +FROM product.catalog_category AS c +JOIN product.product_catalog_bindings AS binding ON binding.category_id = c.id + AND binding.deleted_at IS NULL +JOIN product.products AS p ON p.id = binding.product_id + AND p.tenant_id = $1 + AND p.store_id = $2 + AND p.deleted_at IS NULL +LEFT JOIN product.brands AS b ON b.id = p.brand_id + AND b.tenant_id = $1 + AND b.store_id = $2 + AND b.deleted_at IS NULL +WHERE c.id IN (`+placeholders+`) + 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 + ) +ORDER BY c.id ASC, + CASE WHEN p.brand_id IS NULL THEN 1 ELSE 0 END ASC, + LOWER(CASE + WHEN p.brand_id IS NULL THEN '未设置品牌' + WHEN b.id IS NULL THEN '品牌已删除' + ELSE b.name + END) ASC, + COALESCE(p.brand_id, 0) ASC, + p.created_at DESC, + p.id DESC`, args...) + if err != nil { + return fmt.Errorf("query group brand products: %w", err) + } + defer rows.Close() + + lastBrandKey := make(map[string]string, len(groupsByID)) + for rows.Next() { + var groupID, brandID, productID int64 + var name, spuNo string + if err := rows.Scan(&groupID, &brandID, &name, &productID, &spuNo); err != nil { + return fmt.Errorf("scan group brand product: %w", err) + } + groupKey := formatID(groupID) + group := groupsByID[groupKey] + if group == nil { + continue + } + brandKey := fmt.Sprintf("%d", brandID) + if lastBrandKey[groupKey] != brandKey { + brandIDValue := "" + if brandID != 0 { + brandIDValue = formatID(brandID) + } + group.BrandProducts = append(group.BrandProducts, GroupBrandProductRecord{ + BrandID: brandIDValue, + BrandName: name, + Products: []GroupBrandProductItemRecord{}, + }) + lastBrandKey[groupKey] = brandKey + } + brand := &group.BrandProducts[len(group.BrandProducts)-1] + brand.Products = append(brand.Products, GroupBrandProductItemRecord{ + ProductID: formatID(productID), + SPUNo: spuNo, + }) + } + if err := rows.Err(); err != nil { + return fmt.Errorf("iterate group brand products: %w", err) + } + return nil +} + +func (r *ProductRepository) loadProductByID(ctx context.Context, productID string, scope StoreScope) (*ProductRecord, error) { + products, err := r.loadProductsByIDs(ctx, []string{productID}, scope) if err != nil { return nil, err } if len(products) == 0 { return nil, ErrProductNotFound } - return products[0], nil + product := products[0] + product.Scope = scope + return product, nil } -func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []string) ([]*ProductRecord, error) { +func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []string, scope StoreScope) ([]*ProductRecord, error) { placeholders := make([]string, len(productIDs)) args := make([]any, len(productIDs)) for i, id := range productIDs { @@ -2329,6 +4643,11 @@ func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs [] placeholders[i] = fmt.Sprintf("$%d", i+1) args[i] = parsed } + storeFilter := "" + if scope.Valid() { + args = append(args, scope.StoreID) + storeFilter = fmt.Sprintf(" AND store_id = $%d", len(args)) + } query := fmt.Sprintf(` SELECT id, @@ -2340,24 +4659,32 @@ SELECT id, COALESCE(to_json(image_ids)::text, '[]'), COALESCE(detail_html, ''), member_discount_enabled, + is_distribution_product, + COALESCE(distribution_product_detail, '{}'::jsonb)::text, goods_type, COALESCE(to_json(service_guarantees)::text, '[]'), status, cross_border, + category_properties, freight_charge_type, freight_fixed_amount, freight_template_id, sale_time_type, scheduled_sale_time, + presale_type, + delivery_time_type, + delivery_start_at, + COALESCE(delivery_after_paid_days, 0), + purchase_limit_quantity, version, deleted_at, created_at, updated_at FROM product.products WHERE id IN (%s) - AND deleted_at IS NULL + AND deleted_at IS NULL%s ORDER BY created_at ASC -`, strings.Join(placeholders, ", ")) +`, strings.Join(placeholders, ", "), storeFilter) rows, err := r.db.QueryContext(ctx, query, args...) if err != nil { @@ -2371,6 +4698,9 @@ ORDER BY created_at ASC if err != nil { return nil, err } + if scope.Valid() { + product.Scope = scope + } products = append(products, product) } if err := rows.Err(); err != nil { @@ -2380,7 +4710,10 @@ ORDER BY created_at ASC return products, nil } -func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) { +func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs, categoryProperties []byte) (*ProductRecord, error) { + if err := requireWriteScope(product.Scope); err != nil { + return nil, err + } id, err := parseID(product.ID, "product id") if err != nil { return nil, err @@ -2400,6 +4733,8 @@ func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs row := tx.QueryRowContext(ctx, ` INSERT INTO product.products ( id, + tenant_id, + store_id, spu_no, title, selling_point, @@ -2408,17 +4743,25 @@ INSERT INTO product.products ( image_ids, detail_html, member_discount_enabled, + is_distribution_product, + distribution_product_detail, goods_type, service_guarantees, status, cross_border, + category_properties, freight_charge_type, freight_fixed_amount, freight_template_id, sale_time_type, - scheduled_sale_time + scheduled_sale_time, + presale_type, + delivery_time_type, + delivery_start_at, + delivery_after_paid_days, + purchase_limit_quantity ) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17::jsonb, $18::jsonb, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28) RETURNING id, spu_no, title, @@ -2428,31 +4771,41 @@ RETURNING id, COALESCE(to_json(image_ids)::text, '[]'), COALESCE(detail_html, ''), member_discount_enabled, + is_distribution_product, + COALESCE(distribution_product_detail, '{}'::jsonb)::text, goods_type, COALESCE(to_json(service_guarantees)::text, '[]'), status, cross_border, + category_properties, freight_charge_type, freight_fixed_amount, freight_template_id, sale_time_type, scheduled_sale_time, + presale_type, + delivery_time_type, + delivery_start_at, + COALESCE(delivery_after_paid_days, 0), + purchase_limit_quantity, version, deleted_at, created_at, updated_at -`, id, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), - product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees), - statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, - int16(product.SaleTimeType), product.ScheduledSaleTime) +`, id, product.Scope.TenantID, product.Scope.StoreID, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), + product.DetailHTML, product.MemberDiscountEnabled, product.IsDistributionProduct, product.DistributionProductDetailJSON, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees), + statusToDB(product.Status), attrs, categoryProperties, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, + int16(product.SaleTimeType), product.ScheduledSaleTime, + int16(product.PresaleType), int16(product.DeliveryTimeType), deliveryStartAtArgument(product), deliveryAfterPaidDaysArgument(product), product.PurchaseLimitQuantity) createdProduct, err := scanProduct(row) if err != nil { - if isPostgresConstraintError(err, "23505", "uq_products_spu_no") { + if isPostgresConstraintError(err, "23505", "uq_products_store_spu_no") || isPostgresConstraintError(err, "23505", "uq_products_spu_no") { return nil, fmt.Errorf("%w: %s", ErrDuplicateSPUNo, product.SPUNo) } return nil, fmt.Errorf("insert product: %w", err) } + createdProduct.Scope = product.Scope return createdProduct, nil } @@ -2464,6 +4817,17 @@ func isPostgresConstraintError(err error, code, constraint string) bool { return pgErr.Code == code && pgErr.ConstraintName == constraint } +func categoryNameConflictError(err error) error { + switch { + case isPostgresConstraintError(err, "23505", "uq_product_category_group_normalized_name"): + return ErrGroupNameExists + case isPostgresConstraintError(err, "23505", "uq_product_category_sibling_normalized_name"): + return ErrCategoryNameExists + default: + return nil + } +} + func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) (*SKURecord, error) { attrs, err := normalizeAttributesJSON(sku.AttributesJSON) if err != nil { @@ -2480,13 +4844,18 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord) } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status) -VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8) +INSERT INTO product.product_items (id, product_id, sku_no, name, price, supply_price, weight_kg, barcode, image_ids, attributes, status, tenant_id, store_id) +SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, $11, p.tenant_id, p.store_id +FROM product.products p +WHERE p.id = $2 RETURNING id, product_id, sku_no, name, price, + supply_price, + weight_kg, + barcode, COALESCE(to_json(image_ids)::text, '[]'), attributes, status, @@ -2504,7 +4873,7 @@ RETURNING id, NULL::integer, NULL::timestamptz, NULL::timestamptz -`, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) +`, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, nullableInt64(sku.SupplyPrice), nullableFloat64(sku.WeightKg), nullString(sku.Barcode), stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) createdSKU, err := scanSKU(row) if err != nil { @@ -2589,9 +4958,9 @@ func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID } _, err = tx.ExecContext(ctx, ` -INSERT INTO product.product_category_bindings (id, product_id, category_id) +INSERT INTO product.product_catalog_bindings (id, product_id, category_id) VALUES ($1, $2, $3) -ON CONFLICT (product_id, category_id) DO NOTHING +ON CONFLICT (product_id, category_id) WHERE deleted_at IS NULL DO NOTHING `, parsedBindingID, parsedProductID, parsedCategoryID) if err != nil { return fmt.Errorf("insert category binding: %w", err) @@ -2599,7 +4968,10 @@ ON CONFLICT (product_id, category_id) DO NOTHING return nil } -func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord) (*CategoryRecord, error) { +func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord, scope StoreScope) (*CategoryRecord, error) { + if err := requireWriteScope(scope); err != nil { + return nil, err + } id, err := parseID(category.ID, "category id") if err != nil { return nil, err @@ -2613,19 +4985,26 @@ func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord } parentID = sql.NullInt64{Int64: parsedParentID, Valid: true} } + campaignID, err := nullableCategoryCampaignID(&category.CampaignID) + if err != nil { + return nil, err + } row := tx.QueryRowContext(ctx, ` -INSERT INTO product.product_category ( +INSERT INTO product.catalog_category ( id, + tenant_id, + store_id, node_type, name, parent_id, level, image_ids, sort_num, - status + status, + campaign_id ) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id, node_type, name, @@ -2634,10 +5013,14 @@ RETURNING id, COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, + campaign_id, version -`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status)) +`, id, scope.TenantID, scope.StoreID, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status), campaignID) createdCategory, err := scanCategory(row) + if nameConflict := categoryNameConflictError(err); nameConflict != nil { + return nil, nameConflict + } if err != nil { return nil, fmt.Errorf("insert category node: %w", err) } @@ -2667,6 +5050,9 @@ SELECT pi.id, pi.sku_no, pi.name, pi.price, + pi.supply_price, + pi.weight_kg, + pi.barcode, COALESCE(to_json(pi.image_ids)::text, '[]'), pi.attributes, pi.status, @@ -2736,6 +5122,9 @@ SELECT pi.id, pi.sku_no, pi.name, pi.price, + pi.supply_price, + pi.weight_kg, + pi.barcode, COALESCE(to_json(pi.image_ids)::text, '[]'), pi.attributes, pi.status, @@ -2786,10 +5175,11 @@ type rowScanner interface { func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { var ( - rec CategoryProductRecord - id int64 - status int16 - imageIDsJSON string + rec CategoryProductRecord + id int64 + status int16 + imageIDsJSON string + categoryPropertiesJSON string ) if err := scanner.Scan( &rec.UpdatedAt, @@ -2799,6 +5189,9 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { &rec.SPUNo, &status, &imageIDsJSON, + &categoryPropertiesJSON, + &rec.IsDistributionProduct, + &rec.PresaleType, &rec.Price, &rec.SoldQuantity, &rec.StockQuantity, @@ -2814,26 +5207,34 @@ func scanCategoryProduct(scanner rowScanner) (*CategoryProductRecord, error) { return nil, fmt.Errorf("unmarshal category product image_ids: %w", err) } rec.ImageIDs = imageIDs + rec.CategoryPropertiesJSON = categoryPropertiesJSON + if rec.CategoryPropertiesJSON == "" { + rec.CategoryPropertiesJSON = "{}" + } return &rec, nil } func scanProduct(scanner rowScanner) (*ProductRecord, error) { var ( - rec ProductRecord - id int64 - brandID sql.NullInt64 - supplierID sql.NullInt64 - imageIDsJSON string - serviceGuaranteesJSON string - goodsType int16 - status int16 - attrsJSON []byte - freightChargeType int16 - freightTemplateID sql.NullInt64 - saleTimeType int16 - scheduledSaleTime sql.NullTime - version int32 - deletedAt sql.NullTime + rec ProductRecord + id int64 + brandID sql.NullInt64 + supplierID sql.NullInt64 + imageIDsJSON string + serviceGuaranteesJSON string + goodsType int16 + status int16 + attrsJSON []byte + categoryPropertiesJSON []byte + freightChargeType int16 + freightTemplateID sql.NullInt64 + saleTimeType int16 + scheduledSaleTime sql.NullTime + presaleType int16 + deliveryTimeType int16 + deliveryStartAt sql.NullTime + version int32 + deletedAt sql.NullTime ) if err := scanner.Scan( &id, @@ -2845,15 +5246,23 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { &imageIDsJSON, &rec.DetailHTML, &rec.MemberDiscountEnabled, + &rec.IsDistributionProduct, + &rec.DistributionProductDetailJSON, &goodsType, &serviceGuaranteesJSON, &status, &attrsJSON, + &categoryPropertiesJSON, &freightChargeType, &rec.FreightFixedAmount, &freightTemplateID, &saleTimeType, &scheduledSaleTime, + &presaleType, + &deliveryTimeType, + &deliveryStartAt, + &rec.DeliveryAfterPaidDays, + &rec.PurchaseLimitQuantity, &version, &deletedAt, &rec.CreatedAt, @@ -2886,6 +5295,10 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { if rec.CrossBorderJSON == "" { rec.CrossBorderJSON = "{}" } + rec.CategoryPropertiesJSON = string(categoryPropertiesJSON) + if rec.CategoryPropertiesJSON == "" { + rec.CategoryPropertiesJSON = "{}" + } if len(attrsJSON) > 0 { if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil { return nil, fmt.Errorf("unmarshal product attrs: %w", err) @@ -2896,21 +5309,45 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) { } rec.FreightChargeType = int32(freightChargeType) rec.SaleTimeType = int32(saleTimeType) + rec.PresaleType = int32(presaleType) + rec.DeliveryTimeType = int32(deliveryTimeType) if scheduledSaleTime.Valid { rec.ScheduledSaleTime = timePtr(scheduledSaleTime.Time) } + if deliveryStartAt.Valid { + rec.DeliveryStartAt = timePtr(deliveryStartAt.Time) + } if deletedAt.Valid { rec.DeletedAt = timePtr(deletedAt.Time) } return &rec, nil } +// deliveryStartAtArgument and deliveryAfterPaidDaysArgument preserve the +// database invariant that non-applicable delivery promise values are NULL. +func deliveryStartAtArgument(product ProductRecord) any { + if product.DeliveryTimeType != 1 { + return nil + } + return product.DeliveryStartAt +} + +func deliveryAfterPaidDaysArgument(product ProductRecord) any { + if product.DeliveryTimeType != 2 { + return nil + } + return product.DeliveryAfterPaidDays +} + func scanSKU(scanner rowScanner) (*SKURecord, error) { var ( rec SKURecord id int64 productID int64 skuNo sql.NullString + supplyPrice sql.NullInt64 + weightKg sql.NullFloat64 + barcode sql.NullString imageIDsJSON string attrsJSON []byte status int16 @@ -2933,6 +5370,9 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { &skuNo, &rec.Name, &rec.Price, + &supplyPrice, + &weightKg, + &barcode, &imageIDsJSON, &attrsJSON, &status, @@ -2959,6 +5399,17 @@ func scanSKU(scanner rowScanner) (*SKURecord, error) { if skuNo.Valid { rec.SKUNo = skuNo.String } + if supplyPrice.Valid { + value := supplyPrice.Int64 + rec.SupplyPrice = &value + } + if weightKg.Valid { + value := weightKg.Float64 + rec.WeightKg = &value + } + if barcode.Valid { + rec.Barcode = barcode.String + } imageIDs, err := parseStringArrayJSON(imageIDsJSON) if err != nil { return nil, fmt.Errorf("unmarshal sku image_ids: %w", err) @@ -3025,6 +5476,43 @@ func scanInventory(scanner rowScanner) (*InventoryRecord, error) { return &rec, nil } +func scanGroup(scanner rowScanner) (*CategoryRecord, error) { + var ( + rec CategoryRecord + id int64 + parentID sql.NullInt64 + imageIDsJSON []byte + nodeType int16 + level int16 + status int16 + campaignID sql.NullInt64 + isLeaf bool + ) + if err := scanner.Scan( + &id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &campaignID, &rec.Version, &rec.ProductCount, &isLeaf, + ); err != nil { + return nil, fmt.Errorf("scan group: %w", err) + } + + rec.ID = formatID(id) + rec.NodeType = int32(nodeType) + if parentID.Valid { + rec.ParentID = formatID(parentID.Int64) + } + rec.Level = int32(level) + imageIDs, err := parseStringArrayJSON(string(imageIDsJSON)) + if err != nil { + return nil, fmt.Errorf("unmarshal group image_ids: %w", err) + } + rec.ImageIDs = imageIDs + rec.IsLeaf = isLeaf + rec.Status = int32(status) + if campaignID.Valid { + rec.CampaignID = formatID(campaignID.Int64) + } + return &rec, nil +} + func scanCategory(scanner rowScanner) (*CategoryRecord, error) { var ( rec CategoryRecord @@ -3034,9 +5522,10 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { nodeType int16 level int16 status int16 + campaignID sql.NullInt64 ) if err := scanner.Scan( - &id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &rec.Version, + &id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &campaignID, &rec.Version, ); err != nil { return nil, fmt.Errorf("scan category: %w", err) } @@ -3053,6 +5542,9 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { } rec.ImageIDs = imageIDs rec.Status = int32(status) + if campaignID.Valid { + rec.CampaignID = formatID(campaignID.Int64) + } return &rec, nil } @@ -3084,6 +5576,22 @@ func productCrossBorderJSON(product ProductRecord) ([]byte, error) { return attrs, nil } +func productCategoryPropertiesJSON(product ProductRecord) ([]byte, error) { + raw := strings.TrimSpace(product.CategoryPropertiesJSON) + if raw == "" { + return []byte("{}"), nil + } + var properties map[string]any + if err := json.Unmarshal([]byte(raw), &properties); err != nil || properties == nil { + return nil, errors.New("category_properties must be a JSON object") + } + normalized, err := json.Marshal(properties) + if err != nil { + return nil, fmt.Errorf("marshal category_properties: %w", err) + } + return normalized, nil +} + func applySKUAttributes(rec *SKURecord) error { if rec == nil { return nil @@ -3181,6 +5689,45 @@ func nullString(raw string) sql.NullString { return sql.NullString{String: value, Valid: true} } +// PromoteDueScheduledSales sets due scheduled products to ON_SALE (status=2). +func (r *ProductRepository) PromoteDueScheduledSales(ctx context.Context, now time.Time) (int64, error) { + res, err := r.db.ExecContext(ctx, ` +UPDATE product.products +SET status = 2, + sale_time_type = 1, + scheduled_sale_time = NULL, + version = version + 1, + updated_at = NOW() +WHERE deleted_at IS NULL + AND sale_time_type = 2 + AND scheduled_sale_time IS NOT NULL + AND scheduled_sale_time <= $1 + AND status <> 2 +`, now) + if err != nil { + return 0, fmt.Errorf("promote scheduled sales: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return 0, err + } + return n, nil +} + +func nullableInt64(value *int64) any { + if value == nil { + return nil + } + return *value +} + +func nullableFloat64(value *float64) any { + if value == nil { + return nil + } + return *value +} + func stringSliceOrEmpty(values []string) []string { if values == nil { return []string{} @@ -3205,7 +5752,7 @@ func statusToDB(status productv1.ProductStatus) int16 { return 1 case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE: return 2 - case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE: + case productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT: return 3 default: return 1 @@ -3219,7 +5766,7 @@ func statusFromDB(status int16) productv1.ProductStatus { case 2: return productv1.ProductStatus_PRODUCT_STATUS_ON_SALE case 3: - return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE + return productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT default: return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED } diff --git a/internal/repository/product_repository_test.go b/internal/repository/product_repository_test.go index 45de7b4..6347ab7 100644 --- a/internal/repository/product_repository_test.go +++ b/internal/repository/product_repository_test.go @@ -1,6 +1,11 @@ package repository -import "testing" +import ( + "strings" + "testing" + + productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" +) func TestEscapeLikeLiteral(t *testing.T) { input := `100%_off\\bundle` @@ -37,3 +42,60 @@ func TestAggregateInventoryAdjustmentsRejectsInvalidSKUID(t *testing.T) { 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) + } + } +} diff --git a/internal/repository/store_scope.go b/internal/repository/store_scope.go new file mode 100644 index 0000000..f43674f --- /dev/null +++ b/internal/repository/store_scope.go @@ -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 +} diff --git a/internal/repository/store_scope_test.go b/internal/repository/store_scope_test.go new file mode 100644 index 0000000..6182719 --- /dev/null +++ b/internal/repository/store_scope_test.go @@ -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") + } +} diff --git a/internal/server/catalog_master_server.go b/internal/server/catalog_master_server.go new file mode 100644 index 0000000..1ae8024 --- /dev/null +++ b/internal/server/catalog_master_server.go @@ -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") + } +} diff --git a/internal/server/category_image_ids_test.go b/internal/server/category_image_ids_test.go index e148ee9..d00ee87 100644 --- a/internal/server/category_image_ids_test.go +++ b/internal/server/category_image_ids_test.go @@ -29,3 +29,42 @@ func TestCategoryImageIDsRoundTripThroughExistingProtoField(t *testing.T) { 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) + } +} diff --git a/internal/server/category_name_test.go b/internal/server/category_name_test.go new file mode 100644 index 0000000..d01f56d --- /dev/null +++ b/internal/server/category_name_test.go @@ -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) + } +} diff --git a/internal/server/freight_template_server.go b/internal/server/freight_template_server.go new file mode 100644 index 0000000..815f6ee --- /dev/null +++ b/internal/server/freight_template_server.go @@ -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) + } +} diff --git a/internal/server/freight_template_server_test.go b/internal/server/freight_template_server_test.go new file mode 100644 index 0000000..294cf1a --- /dev/null +++ b/internal/server/freight_template_server_test.go @@ -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) + } +} diff --git a/internal/server/get_product_by_sku_test.go b/internal/server/get_product_by_sku_test.go index 338ce32..c59ca15 100644 --- a/internal/server/get_product_by_sku_test.go +++ b/internal/server/get_product_by_sku_test.go @@ -10,10 +10,10 @@ import ( 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) _, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{}) - if status.Code(err) != codes.InvalidArgument { - t.Fatalf("err = %v", err) + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("err = %v, want FailedPrecondition", err) } } diff --git a/internal/server/html_sanitize.go b/internal/server/html_sanitize.go new file mode 100644 index 0000000..2d6ccc0 --- /dev/null +++ b/internal/server/html_sanitize.go @@ -0,0 +1,42 @@ +package server + +import ( + "regexp" + "strings" +) + +var ( + reScriptTag = regexp.MustCompile(`(?is)]*>.*?`) + reIFrameTag = regexp.MustCompile(`(?is)]*>.*?`) + reObjectTag = regexp.MustCompile(`(?is)]*>.*?`) + reEmbedTag = regexp.MustCompile(`(?is)]*>.*?`) + 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") diff --git a/internal/server/list_product_skus_test.go b/internal/server/list_product_skus_test.go new file mode 100644 index 0000000..0ef8c22 --- /dev/null +++ b/internal/server/list_product_skus_test.go @@ -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) + } +} diff --git a/internal/server/list_products_filter_test.go b/internal/server/list_products_filter_test.go new file mode 100644 index 0000000..06c2a42 --- /dev/null +++ b/internal/server/list_products_filter_test.go @@ -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") + } +} diff --git a/internal/server/product_batch_server.go b/internal/server/product_batch_server.go new file mode 100644 index 0000000..68cd528 --- /dev/null +++ b/internal/server/product_batch_server.go @@ -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 +} diff --git a/internal/server/product_category_ids_test.go b/internal/server/product_category_ids_test.go new file mode 100644 index 0000000..bba4dce --- /dev/null +++ b/internal/server/product_category_ids_test.go @@ -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") + } +} diff --git a/internal/server/product_category_platform_test.go b/internal/server/product_category_platform_test.go new file mode 100644 index 0000000..c5bf9e0 --- /dev/null +++ b/internal/server/product_category_platform_test.go @@ -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") + } +} diff --git a/internal/server/product_category_server.go b/internal/server/product_category_server.go new file mode 100644 index 0000000..2a8d358 --- /dev/null +++ b/internal/server/product_category_server.go @@ -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()) + } +} diff --git a/internal/server/product_codes_test.go b/internal/server/product_codes_test.go new file mode 100644 index 0000000..4ea5f7c --- /dev/null +++ b/internal/server/product_codes_test.go @@ -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) + } +} diff --git a/internal/server/product_create_errors.go b/internal/server/product_create_errors.go new file mode 100644 index 0000000..b122ebb --- /dev/null +++ b/internal/server/product_create_errors.go @@ -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 "" +} diff --git a/internal/server/product_create_errors_test.go b/internal/server/product_create_errors_test.go new file mode 100644 index 0000000..8d9b8eb --- /dev/null +++ b/internal/server/product_create_errors_test.go @@ -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) + } + } +} diff --git a/internal/server/product_cross_border_test.go b/internal/server/product_cross_border_test.go new file mode 100644 index 0000000..077d29b --- /dev/null +++ b/internal/server/product_cross_border_test.go @@ -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") + } +} diff --git a/internal/server/product_freight_charge_test.go b/internal/server/product_freight_charge_test.go new file mode 100644 index 0000000..1800c41 --- /dev/null +++ b/internal/server/product_freight_charge_test.go @@ -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) + } + }) + } +} diff --git a/internal/server/product_presale_configuration_test.go b/internal/server/product_presale_configuration_test.go new file mode 100644 index 0000000..0936d53 --- /dev/null +++ b/internal/server/product_presale_configuration_test.go @@ -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) + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3f274ef..071ceef 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -12,6 +12,7 @@ import ( "time" "unicode/utf8" + "github.com/jackc/pgx/v5/pgconn" "go.opentelemetry.io/otel/attribute" otelcodes "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" @@ -20,6 +21,7 @@ import ( "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/fieldmaskpb" + "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" @@ -36,16 +38,19 @@ const ( categoryNodeType = int32(1) groupNodeType = int32(2) - defaultNodeStatus = int32(1) - maxNodeNameLength = 100 - maxProductsPerGroupRequest = 100 - maxCartItemProductBatchSize = 100 - maxSearchKeywordLength = 50 + defaultNodeStatus = int32(1) + maxNodeNameLength = 100 + maxProductsPerGroupRequest = 100 + maxCartItemProductBatchSize = 100 + maxStorefrontProductBatchSize = 100 + maxSearchKeywordLength = 50 + maxProductTitleLength = 200 ) // ProductServer implements productv1.ProductServiceServer. type ProductServer struct { productv1.UnimplementedProductServiceServer + productv1.UnimplementedProductCategoryServiceServer repo *repository.ProductRepository idgen *idgen.Generator @@ -72,12 +77,29 @@ func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Gen // CreateProduct creates a product SPU and optional SKU list. func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.CreateProductRequest) (*productv1.CreateProductResponse, error) { if req == nil { - return nil, status.Error(codes.InvalidArgument, "request is required") + return nil, productCreateError(codes.InvalidArgument, "request is required", "$") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err } product, skus, err := productFromCreateRequest(req) if err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) + return nil, productCreateError(codes.InvalidArgument, err.Error(), productCreateFieldFromMessage(err.Error())) + } + product.Scope = scope + if err := s.repo.ValidateProductMasterRefs(ctx, product.SupplierID, product.BrandID, scope); err != nil { + catalogErr := catalogGRPCError(err) + return nil, productCreateError(status.Code(catalogErr), status.Convert(catalogErr).Message(), productMasterReferenceField(err)) + } + if product.FreightChargeType == 2 { + if err := s.repo.FreightTemplateExists(ctx, product.FreightTemplateID, scope); err != nil { + if errors.Is(err, repository.ErrFreightTemplateNotFound) { + return nil, productCreateError(codes.InvalidArgument, "freight_template_id not found or disabled", "freight_template_id") + } + return nil, status.Errorf(codes.Internal, "validate freight template: %v", err) + } } if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") @@ -90,6 +112,12 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create for range product.LeafCategoryIDs { product.CategoryBindingIDs = append(product.CategoryBindingIDs, s.idgen.NextString()) } + for range product.GroupIDs { + product.GroupBindingIDs = append(product.GroupBindingIDs, s.idgen.NextString()) + } + for range product.ProductCategoryIDs { + product.ProductCategoryBindingIDs = append(product.ProductCategoryBindingIDs, s.idgen.NextString()) + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( attribute.String("product.spu_no", product.SPUNo), @@ -103,10 +131,16 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("create product failed", zap.String("spu_no", product.SPUNo), zap.Error(err)) if errors.Is(err, repository.ErrDuplicateSPUNo) { - return nil, status.Errorf(codes.AlreadyExists, "spu_no already exists: %s", product.SPUNo) + return nil, productCreateError(codes.AlreadyExists, fmt.Sprintf("spu_no already exists: %s", product.SPUNo), "spu_no") } if errors.Is(err, repository.ErrInvalidLeafCategory) { - return nil, status.Error(codes.InvalidArgument, err.Error()) + return nil, productCreateError(codes.InvalidArgument, err.Error(), "leaf_catalog_category_ids") + } + if errors.Is(err, repository.ErrInvalidProductGroup) { + return nil, productCreateError(codes.InvalidArgument, err.Error(), "group_ids") + } + if errors.Is(err, repository.ErrInvalidProductCategory) { + return nil, productCreateError(codes.InvalidArgument, err.Error(), "product_category_ids") } return nil, status.Errorf(codes.Internal, "create product: %v", err) } @@ -133,14 +167,18 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create // GetProduct returns a single SPU and its SKU list. func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProductRequest) (*productv1.GetProductResponse, error) { - if req == nil || req.GetProductId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetProductId() == "" { return nil, status.Error(codes.InvalidArgument, "product_id is required") } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() - product, skus, err := s.repo.GetProduct(dbCtx, req.GetProductId()) + product, skus, err := s.repo.GetProduct(dbCtx, req.GetProductId(), scope) if errors.Is(err, repository.ErrProductNotFound) { dbSpan.SetStatus(otelcodes.Error, "product not found") return nil, status.Error(codes.NotFound, "product not found") @@ -151,15 +189,67 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc s.observer.Logger(ctx).Error("get product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "get product: %v", err) } + totalSoldQuantity, err := s.repo.GetProductTotalSoldQuantity(dbCtx, req.GetProductId(), scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("get product total sold quantity failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "get product total sold quantity: %v", err) + } return &productv1.GetProductResponse{ - Product: toProtoProduct(product, skus), + Product: toProtoProduct(product, skus), + TotalSoldQuantity: totalSoldQuantity, + }, nil +} + +// ListProductSKUs returns the compact current-SKU stock projection for one SPU. +func (s *ProductServer) ListProductSKUs(ctx context.Context, req *productv1.ListProductSKUsRequest) (*productv1.ListProductSKUsResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if err := validatePositiveID(req.GetProductId(), "product_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.sku.list", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) + defer dbSpan.End() + + skus, err := s.repo.ListProductSKUStocks(dbCtx, req.GetProductId(), scope) + if errors.Is(err, repository.ErrProductNotFound) { + dbSpan.SetStatus(otelcodes.Error, "product not found") + return nil, status.Error(codes.NotFound, "product not found") + } + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("list product skus failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "list product skus: %v", err) + } + + result := make([]*productv1.ProductSKUStock, 0, len(skus)) + for _, sku := range skus { + result = append(result, &productv1.ProductSKUStock{ + Id: sku.ID, + Name: sku.Name, + StockQuantity: sku.StockQuantity, + SupplyPrice: sku.SupplyPrice, + }) + } + return &productv1.ListProductSKUsResponse{ + Skus: result, + Total: int32(len(result)), }, nil } // GetProductBySku returns the SPU that owns the SKU. func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetProductBySkuRequest) (*productv1.GetProductResponse, error) { - if req == nil || req.GetSkuId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetSkuId() == "" { return nil, status.Error(codes.InvalidArgument, "sku_id is required") } if err := validatePositiveID(req.GetSkuId(), "sku_id"); err != nil { @@ -169,7 +259,7 @@ func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetP dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.load_by_sku", trace.WithAttributes(attribute.String("sku.id", req.GetSkuId()))) defer dbSpan.End() - product, skus, err := s.repo.GetProductBySKU(dbCtx, req.GetSkuId()) + product, skus, err := s.repo.GetProductBySKU(dbCtx, req.GetSkuId(), scope) if errors.Is(err, repository.ErrSKUNotFound) { dbSpan.SetStatus(otelcodes.Error, "sku not found") return nil, status.Error(codes.NotFound, "sku not found") @@ -194,6 +284,10 @@ func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetP // Missing and soft-deleted records are represented by their default invalid state rather // than failing the whole batch; malformed requests still return InvalidArgument. func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *productv1.BatchGetCartItemProductRequest) (*productv1.BatchGetCartItemProductResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } if req == nil || len(req.GetItems()) == 0 { return nil, status.Error(codes.InvalidArgument, "items is required") } @@ -234,7 +328,7 @@ func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *produc )) defer dbSpan.End() - records, err := s.repo.BatchGetCartItemProducts(dbCtx, lookups) + records, err := s.repo.BatchGetCartItemProducts(dbCtx, lookups, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -256,16 +350,77 @@ func (s *ProductServer) BatchGetCartItemProduct(ctx context.Context, req *produc return &productv1.BatchGetCartItemProductResponse{Items: items}, nil } +// BatchGetStorefrontProductSKUs returns the current sellable SKU prices needed +// to calculate product-card promotion display data in one downstream call. +func (s *ProductServer) BatchGetStorefrontProductSKUs(ctx context.Context, req *productv1.BatchGetStorefrontProductSKUsRequest) (*productv1.BatchGetStorefrontProductSKUsResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if len(req.GetProductIds()) == 0 { + return nil, status.Error(codes.InvalidArgument, "product_ids is required") + } + if len(req.GetProductIds()) > maxStorefrontProductBatchSize { + return nil, status.Errorf(codes.InvalidArgument, "product_ids must contain at most %d entries", maxStorefrontProductBatchSize) + } + + productIDs := make([]string, 0, len(req.GetProductIds())) + seen := make(map[string]struct{}, len(req.GetProductIds())) + for index, productID := range req.GetProductIds() { + if err := validatePositiveID(productID, "product_id"); err != nil { + return nil, status.Errorf(codes.InvalidArgument, "product_ids[%d]: %v", index, err) + } + if _, exists := seen[productID]; exists { + continue + } + seen[productID] = struct{}{} + productIDs = append(productIDs, productID) + } + + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.storefront_skus.batch_get", trace.WithAttributes( + attribute.Int("product.count", len(productIDs)), + )) + defer dbSpan.End() + records, err := s.repo.BatchGetStorefrontProductSKUs(dbCtx, productIDs, scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + s.observer.Logger(ctx).Error("batch get storefront product skus failed", zap.Error(err)) + return nil, status.Errorf(codes.Internal, "batch get storefront product skus: %v", err) + } + + byProduct := make(map[string][]*productv1.StorefrontProductSKU, len(productIDs)) + for _, record := range records { + byProduct[record.ProductID] = append(byProduct[record.ProductID], &productv1.StorefrontProductSKU{ + SkuId: record.SKUID, + OriginalPrice: record.Price, + }) + } + products := make([]*productv1.StorefrontProductSKUs, 0, len(byProduct)) + for _, productID := range productIDs { + skus := byProduct[productID] + if len(skus) == 0 { + continue + } + products = append(products, &productv1.StorefrontProductSKUs{ProductId: productID, Skus: skus}) + } + return &productv1.BatchGetStorefrontProductSKUsResponse{Products: products}, nil +} + // UpdateProduct updates mutable SPU fields and optionally patches or replaces its SKU set. func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.UpdateProductRequest) (*productv1.UpdateProductResponse, error) { - if req == nil || req.GetProductId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetProductId() == "" { return nil, status.Error(codes.InvalidArgument, "product_id is required") } if req.GetExpectedVersion() < 0 { return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") } - current, _, err := s.repo.GetProduct(ctx, req.GetProductId()) + current, _, err := s.repo.GetProduct(ctx, req.GetProductId(), scope) if errors.Is(err, repository.ErrProductNotFound) { return nil, status.Error(codes.NotFound, "product not found") } @@ -285,15 +440,29 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update if len(req.GetUpdateMask().GetPaths()) == 0 && skuChange == nil { return nil, status.Error(codes.InvalidArgument, "at least one product field or sku_change is required") } - if err := validateProductForUpdate(merged); err != nil { + if err := validateProductForUpdate(&merged); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } - + if err := s.repo.ValidateProductMasterRefs(ctx, merged.SupplierID, merged.BrandID, scope); err != nil { + return nil, catalogGRPCError(err) + } + if merged.FreightChargeType == 2 { + if err := s.repo.FreightTemplateExists(ctx, merged.FreightTemplateID, scope); err != nil { + if errors.Is(err, repository.ErrFreightTemplateNotFound) { + return nil, status.Error(codes.InvalidArgument, "freight_template_id not found or disabled") + } + return nil, status.Errorf(codes.Internal, "validate freight template: %v", err) + } + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() var leafCategoryIDs *[]string var categoryBindingIDs []string - if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_category_ids") { + var groupIDs *[]string + var groupBindingIDs []string + var productCategoryIDs *[]string + var productCategoryBindingIDs []string + if containsUpdatePath(req.GetUpdateMask().GetPaths(), "leaf_catalog_category_ids") { leafCategoryIDs = &merged.LeafCategoryIDs if s.idgen == nil { return nil, status.Error(codes.Internal, "id generator is not configured") @@ -302,12 +471,35 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update categoryBindingIDs = append(categoryBindingIDs, s.idgen.NextString()) } } + if containsUpdatePath(req.GetUpdateMask().GetPaths(), "group_ids") { + groupIDs = &merged.GroupIDs + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + for range merged.GroupIDs { + groupBindingIDs = append(groupBindingIDs, s.idgen.NextString()) + } + } + if containsUpdatePath(req.GetUpdateMask().GetPaths(), "product_category_ids") { + productCategoryIDs = &merged.ProductCategoryIDs + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + for range merged.ProductCategoryIDs { + productCategoryBindingIDs = append(productCategoryBindingIDs, s.idgen.NextString()) + } + } result, err := s.repo.UpdateProductWithSKUChange(dbCtx, repository.ProductUpdateInput{ - Product: merged, - ExpectedVersion: req.GetExpectedVersion(), - SKUChange: skuChange, - LeafCategoryIDs: leafCategoryIDs, - CategoryBindingIDs: categoryBindingIDs, + Product: merged, + ExpectedVersion: req.GetExpectedVersion(), + SKUChange: skuChange, + LeafCategoryIDs: leafCategoryIDs, + CategoryBindingIDs: categoryBindingIDs, + GroupIDs: groupIDs, + GroupBindingIDs: groupBindingIDs, + ProductCategoryIDs: productCategoryIDs, + ProductCategoryBindingIDs: productCategoryBindingIDs, + Scope: scope, }) if err != nil { dbSpan.RecordError(err) @@ -323,13 +515,17 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update return nil, status.Error(codes.NotFound, err.Error()) case errors.Is(err, repository.ErrInvalidLeafCategory): return nil, status.Error(codes.InvalidArgument, err.Error()) + case errors.Is(err, repository.ErrInvalidProductGroup): + return nil, status.Error(codes.InvalidArgument, err.Error()) + case errors.Is(err, repository.ErrInvalidProductCategory): + return nil, status.Error(codes.InvalidArgument, err.Error()) default: s.observer.Logger(ctx).Error("update product failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) return nil, status.Errorf(codes.Internal, "update product: %v", err) } } - updated, skus, err := s.repo.GetProduct(ctx, req.GetProductId()) + updated, skus, err := s.repo.GetProduct(ctx, req.GetProductId(), scope) if err != nil { return nil, status.Errorf(codes.Internal, "load updated product: %v", err) } @@ -339,14 +535,63 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update }, nil } +// UpdateProductFreightCharge updates only one product's freight configuration, +// locating it by the store-scoped SPU business number. +func (s *ProductServer) UpdateProductFreightCharge(ctx context.Context, req *productv1.UpdateProductFreightChargeRequest) (*productv1.UpdateProductFreightChargeResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + spuNo, freightChargeType, freightFixedAmount, freightTemplateID, err := productFreightChargeFromUpdateRequest(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if freightChargeType == 2 { + if err := validatePositiveID(freightTemplateID, "freight_template_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if err := s.repo.FreightTemplateExists(ctx, freightTemplateID, scope); err != nil { + if errors.Is(err, repository.ErrFreightTemplateNotFound) { + return nil, status.Error(codes.InvalidArgument, "freight_template_id not found or disabled") + } + return nil, status.Errorf(codes.Internal, "validate freight template: %v", err) + } + } + + updated, err := s.repo.UpdateProductFreightChargeBySPUNo(ctx, spuNo, freightChargeType, freightFixedAmount, freightTemplateID, scope) + if errors.Is(err, repository.ErrProductNotFound) { + return nil, status.Error(codes.NotFound, "product not found") + } + if err != nil { + s.observer.Logger(ctx).Error("update product freight charge failed", zap.String("spu_no", spuNo), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "update product freight charge: %v", err) + } + return &productv1.UpdateProductFreightChargeResponse{ + ProductId: updated.ProductID, + SpuNo: updated.SPUNo, + FreightChargeType: updated.FreightChargeType, + FreightFixedAmount: updated.FreightFixedAmount, + FreightTemplateId: updated.FreightTemplateID, + Version: updated.Version, + UpdatedAt: updated.UpdatedAt.UTC().Format(time.RFC3339Nano), + }, nil +} + // UpdateProductStatus changes the product lifecycle status. func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1.UpdateProductStatusRequest) (*productv1.UpdateProductStatusResponse, error) { - if req == nil || req.GetProductId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetProductId() == "" { return nil, status.Error(codes.InvalidArgument, "product_id is required") } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.status.update", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) defer dbSpan.End() - updated, err := s.repo.UpdateProductStatus(dbCtx, req.GetProductId(), req.GetStatus(), req.GetExpectedVersion()) + updated, err := s.repo.UpdateProductStatus(dbCtx, req.GetProductId(), req.GetStatus(), req.GetExpectedVersion(), scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -368,9 +613,187 @@ func (s *ProductServer) UpdateProductStatus(ctx context.Context, req *productv1. }, nil } +// TransferProductStore moves a product to another store without changing tenant. +func (s *ProductServer) TransferProductStore(ctx context.Context, req *productv1.TransferProductStoreRequest) (*productv1.TransferProductStoreResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetProductId() == "" { + return nil, status.Error(codes.InvalidArgument, "product_id is required") + } + targetStoreID, err := parsePositiveID(strings.TrimSpace(req.GetTargetStoreId()), "target_store_id") + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.store.transfer", trace.WithAttributes(attribute.String("product.id", req.GetProductId()))) + defer dbSpan.End() + updated, err := s.repo.TransferProductStore(dbCtx, req.GetProductId(), targetStoreID, 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.ErrSameStore): + return nil, status.Error(codes.InvalidArgument, "target store is the current store") + case errors.Is(err, repository.ErrDuplicateSPUNo): + return nil, status.Error(codes.AlreadyExists, err.Error()) + default: + s.observer.Logger(ctx).Error("transfer product store failed", zap.String("product_id", req.GetProductId()), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "transfer product store: %v", err) + } + } + return &productv1.TransferProductStoreResponse{ + ProductId: updated.ProductID, + TenantId: strconv.FormatInt(updated.TenantID, 10), + StoreId: strconv.FormatInt(updated.StoreID, 10), + }, nil +} + +// CopyProductToStore creates a new target-store product instead of moving the +// source record. Source product, SKU, inventory, and material records remain +// untouched. Material IDs must already have been copied by ids-svc-storage. +func (s *ProductServer) CopyProductToStore(ctx context.Context, req *productv1.CopyProductToStoreRequest) (*productv1.CopyProductToStoreResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if err := validatePositiveID(req.GetSourceProductId(), "source_product_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + targetStoreID, err := parsePositiveID(strings.TrimSpace(req.GetTargetStoreId()), "target_store_id") + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if targetStoreID == scope.StoreID { + return nil, status.Error(codes.InvalidArgument, "target store is the current store") + } + if s.idgen == nil { + return nil, status.Error(codes.Internal, "id generator is not configured") + } + + source, sourceSKUs, err := s.repo.GetProduct(ctx, req.GetSourceProductId(), scope) + if errors.Is(err, repository.ErrProductNotFound) { + return nil, status.Error(codes.NotFound, "source product not found") + } + if err != nil { + return nil, status.Errorf(codes.Internal, "load source product: %v", err) + } + mappings, err := productCopyMaterialMap(source, sourceSKUs, req.GetMaterialIdMappings()) + if err != nil { + return nil, status.Error(codes.FailedPrecondition, err.Error()) + } + + targetScope := repository.StoreScope{TenantID: scope.TenantID, StoreID: targetStoreID} + target := *source + target.ID = s.idgen.NextString() + target.Scope = targetScope + target.Status = productv1.ProductStatus_PRODUCT_STATUS_INVENTORY + target.BrandID = "" + target.SupplierID = "" + target.ImageIDs = remapProductCopyImageIDs(source.ImageIDs, mappings) + target.LeafCategoryIDs = nil + target.CategoryBindingIDs = nil + target.GroupIDs = nil + target.GroupBindingIDs = nil + target.Version = 0 + target.DeletedAt = nil + target.CreatedAt = time.Time{} + target.UpdatedAt = time.Time{} + + targetSKUs := make([]repository.SKURecord, 0, len(sourceSKUs)) + for _, sourceSKU := range sourceSKUs { + targetSKU := sourceSKU + targetSKU.ID = s.idgen.NextString() + targetSKU.ProductID = target.ID + targetSKU.ImageIDs = remapProductCopyImageIDs(sourceSKU.ImageIDs, mappings) + targetSKU.StockQuantity = 0 + targetSKU.LockedQuantity = 0 + targetSKU.SoldQuantity = 0 + targetSKU.Version = 0 + targetSKU.DeletedAt = nil + targetSKU.IsArchived = false + targetSKU.ArchivedAt = nil + targetSKU.CreatedAt = time.Time{} + targetSKU.UpdatedAt = time.Time{} + targetSKU.Inventory = &repository.InventoryRecord{ID: s.idgen.NextString()} + targetSKUs = append(targetSKUs, targetSKU) + } + + created, _, err := s.repo.CreateProductWithSKUs(ctx, target, targetSKUs) + if err != nil { + if errors.Is(err, repository.ErrDuplicateSPUNo) { + return nil, status.Error(codes.AlreadyExists, err.Error()) + } + return nil, status.Errorf(codes.Internal, "copy product to target store: %v", err) + } + return &productv1.CopyProductToStoreResponse{ + SourceProductId: req.GetSourceProductId(), + TargetProductId: created.ID, + TenantId: strconv.FormatInt(scope.TenantID, 10), + TargetStoreId: strconv.FormatInt(targetStoreID, 10), + }, nil +} + +func productCopyMaterialMap(product *repository.ProductRecord, skus []repository.SKURecord, mappings []*productv1.MaterialIDMapping) (map[string]string, error) { + required := make(map[string]struct{}) + if product != nil { + for _, imageID := range product.ImageIDs { + required[imageID] = struct{}{} + } + } + for _, sku := range skus { + for _, imageID := range sku.ImageIDs { + required[imageID] = struct{}{} + } + } + resolved := make(map[string]string, len(mappings)) + for _, mapping := range mappings { + if mapping == nil || strings.TrimSpace(mapping.GetSourceMaterialId()) == "" || strings.TrimSpace(mapping.GetTargetMaterialId()) == "" { + return nil, fmt.Errorf("material_id_mappings must contain source and target IDs") + } + if _, err := parsePositiveID(mapping.GetSourceMaterialId(), "source_material_id"); err != nil { + return nil, err + } + if _, err := parsePositiveID(mapping.GetTargetMaterialId(), "target_material_id"); err != nil { + return nil, err + } + if _, exists := resolved[mapping.GetSourceMaterialId()]; exists { + return nil, fmt.Errorf("material_id_mappings contains duplicate source_material_id") + } + resolved[mapping.GetSourceMaterialId()] = mapping.GetTargetMaterialId() + } + if len(required) != len(resolved) { + return nil, fmt.Errorf("material_id_mappings must exactly cover source product images") + } + for sourceID := range required { + if _, ok := resolved[sourceID]; !ok { + return nil, fmt.Errorf("material_id_mappings is missing source material %s", sourceID) + } + } + return resolved, nil +} + +func remapProductCopyImageIDs(imageIDs []string, mappings map[string]string) []string { + result := make([]string, 0, len(imageIDs)) + for _, imageID := range imageIDs { + result = append(result, mappings[imageID]) + } + return result +} + // ListProducts returns a paginated list of all non-deleted products. func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListProductsRequest) (*productv1.ListProductsResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) + filter, err := productListFilterFromRequest(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list", trace.WithAttributes( attribute.Int("page", int(page)), @@ -378,7 +801,30 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro )) defer dbSpan.End() - products, total, err := s.repo.ListProducts(dbCtx, page, pageSize) + if filter.GroupID != "" { + if err := s.repo.ValidateProductGroup(dbCtx, filter.GroupID, scope); err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrInvalidProductGroup) { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + s.observer.Logger(ctx).Error("validate product group filter failed", zap.String("group_id", filter.GroupID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "validate product group filter: %v", err) + } + } + if filter.ProductCategoryID != "" { + if err := s.repo.ValidateProductCategory(dbCtx, filter.ProductCategoryID, scope); err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrProductCategoryNotFound) { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + s.observer.Logger(ctx).Error("validate product category filter failed", zap.String("category_id", filter.ProductCategoryID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "validate product category filter: %v", err) + } + } + + products, total, err := s.repo.ListProducts(dbCtx, page, pageSize, filter, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -402,6 +848,111 @@ func (s *ProductServer) ListProducts(ctx context.Context, req *productv1.ListPro }, nil } +func productListFilterFromRequest(req *productv1.ListProductsRequest) (repository.ProductListFilter, error) { + if req == nil { + return repository.ProductListFilter{}, errors.New("request is required") + } + filter := repository.ProductListFilter{ + TitleKeyword: strings.TrimSpace(req.GetTitleKeyword()), + SPUNo: strings.TrimSpace(req.GetSpuNo()), + GroupID: strings.TrimSpace(req.GetGroupId()), + ProductCategoryID: strings.TrimSpace(req.GetCategoryId()), + } + if utf8.RuneCountInString(filter.TitleKeyword) > maxProductTitleLength { + return repository.ProductListFilter{}, fmt.Errorf("title_keyword must contain at most %d characters", maxProductTitleLength) + } + if utf8.RuneCountInString(filter.SPUNo) > 100 { + return repository.ProductListFilter{}, errors.New("spu_no must contain at most 100 characters") + } + if filter.GroupID != "" { + if err := validatePositiveID(filter.GroupID, "group_id"); err != nil { + return repository.ProductListFilter{}, err + } + } + if filter.ProductCategoryID != "" { + if err := validatePositiveID(filter.ProductCategoryID, "category_id"); err != nil { + return repository.ProductListFilter{}, err + } + } + if req.CreatedAtFrom != nil { + value := req.GetCreatedAtFrom() + if value < 0 { + return repository.ProductListFilter{}, errors.New("created_at_from must be greater than or equal to 0") + } + createdAtFrom := time.UnixMilli(value) + filter.CreatedAtFrom = &createdAtFrom + } + if req.CreatedAtTo != nil { + value := req.GetCreatedAtTo() + if value < 0 { + return repository.ProductListFilter{}, errors.New("created_at_to must be greater than or equal to 0") + } + createdAtTo := time.UnixMilli(value) + filter.CreatedAtTo = &createdAtTo + } + if filter.CreatedAtFrom != nil && filter.CreatedAtTo != nil && filter.CreatedAtFrom.After(*filter.CreatedAtTo) { + return repository.ProductListFilter{}, errors.New("created_at_from must be less than or equal to created_at_to") + } + if req.GoodsType != nil { + goodsType := req.GetGoodsType() + if goodsType < 1 || goodsType > 4 { + return repository.ProductListFilter{}, errors.New("goods_type must be between 1 and 4") + } + filter.GoodsType = &goodsType + } + if req.PresaleType != nil { + presaleType := req.GetPresaleType() + if presaleType < 0 || presaleType > 2 { + return repository.ProductListFilter{}, errors.New("presale_type must be 0, 1, or 2") + } + filter.PresaleType = &presaleType + } + if req.Status != nil { + statusValue := req.GetStatus() + if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && + statusValue != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && + statusValue != productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT { + return repository.ProductListFilter{}, errors.New("status must be 1, 2, or 3") + } + filter.Status = &statusValue + } + if req.SoldQuantityMin != nil { + value := req.GetSoldQuantityMin() + if value < 0 { + return repository.ProductListFilter{}, errors.New("sold_quantity_min must be greater than or equal to 0") + } + filter.SoldQuantityMin = &value + } + if req.SoldQuantityMax != nil { + value := req.GetSoldQuantityMax() + if value < 0 { + return repository.ProductListFilter{}, errors.New("sold_quantity_max must be greater than or equal to 0") + } + filter.SoldQuantityMax = &value + } + if filter.SoldQuantityMin != nil && filter.SoldQuantityMax != nil && *filter.SoldQuantityMin > *filter.SoldQuantityMax { + return repository.ProductListFilter{}, errors.New("sold_quantity_min must be less than or equal to sold_quantity_max") + } + if req.PriceMin != nil { + value := req.GetPriceMin() + if value < 0 { + return repository.ProductListFilter{}, errors.New("price_min must be greater than or equal to 0") + } + filter.PriceMin = &value + } + if req.PriceMax != nil { + value := req.GetPriceMax() + if value < 0 { + return repository.ProductListFilter{}, errors.New("price_max must be greater than or equal to 0") + } + filter.PriceMax = &value + } + if filter.PriceMin != nil && filter.PriceMax != nil && *filter.PriceMin > *filter.PriceMax { + return repository.ProductListFilter{}, errors.New("price_min must be less than or equal to price_max") + } + return filter, nil +} + // SearchProducts returns storefront-visible products whose titles contain the // supplied keyword. Visibility is enforced inside the repository and cannot be // relaxed by callers. @@ -409,6 +960,10 @@ func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.Searc if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } keyword := strings.TrimSpace(req.GetKeyword()) keywordLength := utf8.RuneCountInString(keyword) @@ -424,7 +979,7 @@ func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.Searc )) defer dbSpan.End() - products, total, err := s.repo.SearchProducts(dbCtx, keyword, page, pageSize) + products, total, err := s.repo.SearchProducts(dbCtx, keyword, page, pageSize, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -450,27 +1005,50 @@ func (s *ProductServer) SearchProducts(ctx context.Context, req *productv1.Searc // ListCategoryProducts returns a paginated product list under a category. func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1.ListCategoryProductsRequest) (*productv1.ListCategoryProductsResponse, error) { - if req == nil || req.GetCategoryId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetCategoryId() == "" { return nil, status.Error(codes.InvalidArgument, "category_id is required") } categoryID, err := strconv.ParseInt(req.GetCategoryId(), 10, 64) if err != nil || categoryID <= 0 { return nil, status.Error(codes.InvalidArgument, "category_id must be a positive snowflake id") } + targetNodeType := req.GetTargetNodeType() + if targetNodeType == 0 { + targetNodeType = 1 + } + if targetNodeType != 1 && targetNodeType != 2 { + return nil, status.Error(codes.InvalidArgument, "target_node_type must be category (1) or group (2)") + } + if targetNodeType == 2 { + if err := s.repo.ValidateProductGroup(ctx, req.GetCategoryId(), scope); err != nil { + if errors.Is(err, repository.ErrInvalidProductGroup) { + return nil, status.Error(codes.NotFound, "leaf product group not found") + } + return nil, status.Errorf(codes.Internal, "validate product group: %v", err) + } + } page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_by_category", trace.WithAttributes( attribute.String("category.id", req.GetCategoryId()), + attribute.Int("category.node_type", int(targetNodeType)), attribute.Int("page", int(page)), attribute.Int("page_size", int(pageSize)), )) defer dbSpan.End() - products, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize, req.GetOnlyVisible()) + products, productIDs, total, err := s.repo.ListCategoryProducts(dbCtx, req.GetCategoryId(), page, pageSize, req.GetOnlyVisible(), targetNodeType, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrStorefrontCategoryNotFound) { + return nil, status.Error(codes.NotFound, "catalog category not found") + } s.observer.Logger(ctx).Error("list category products failed", zap.String("category_id", req.GetCategoryId()), zap.Int32("page", page), zap.Int32("page_size", pageSize), zap.Error(err)) return nil, status.Errorf(codes.Internal, "list category products: %v", err) } @@ -488,6 +1066,7 @@ func (s *ProductServer) ListCategoryProducts(ctx context.Context, req *productv1 PageSize: pageSize, Total: total, TotalPages: totalPages(total, pageSize), + ProductIds: productIDs, }, nil } @@ -506,10 +1085,14 @@ func normalizedPage(page, pageSize int32) (int32, int32) { // CountProducts returns product counts grouped by lifecycle status. func (s *ProductServer) CountProducts(ctx context.Context, req *productv1.CountProductsRequest) (*productv1.CountProductsResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.count") defer dbSpan.End() - counts, err := s.repo.CountProducts(dbCtx) + counts, err := s.repo.CountProducts(dbCtx, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -529,6 +1112,10 @@ func (s *ProductServer) CountProducts(ctx context.Context, req *productv1.CountP // ListCategoryTree returns product category nodes as a parent-child hierarchy. func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.ListCategoryTreeRequest) (*productv1.ListCategoryTreeResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } onlyVisible := false if req != nil { onlyVisible = req.GetOnlyVisible() @@ -539,7 +1126,21 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis )) defer dbSpan.End() - categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible) + categoryID := "" + maxDepth := int32(0) + if req != nil { + categoryID = strings.TrimSpace(req.GetCategoryId()) + maxDepth = req.GetMaxDepth() + } + if maxDepth < 0 { + return nil, status.Error(codes.InvalidArgument, "max_depth must be non-negative") + } + if categoryID != "" { + if _, err := normalizeCategoryID(categoryID, "category_id"); err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + } + categories, err := s.repo.ListCategoryTreeNodes(dbCtx, onlyVisible, categoryID, maxDepth, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -561,11 +1162,15 @@ func (s *ProductServer) ListCategoryTree(ctx context.Context, req *productv1.Lis return resp, nil } -// CreateCategoryTree creates a top-level category and optional second-level categories. +// CreateCategoryTree creates a catalog-category subtree at any depth. func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.CreateCategoryTreeRequest) (*productv1.CreateCategoryTreeResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + 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") } @@ -574,10 +1179,7 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } - parent.ID = s.idgen.NextString() - for i := range children { - children[i].ID = s.idgen.NextString() - } + assignCatalogCategoryIDs(&parent, s) dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_category_tree", trace.WithAttributes( attribute.String("category.name", parent.Name), @@ -585,18 +1187,18 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C )) defer dbSpan.End() - createdParent, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, parent, children) + createdParent, _, err := s.repo.CreateCatalogCategoryTree(dbCtx, parent, children, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrCategoryNameExists) { + return nil, status.Error(codes.AlreadyExists, "category name already exists") + } s.observer.Logger(ctx).Error("create category tree failed", zap.String("category_name", parent.Name), zap.Error(err)) return nil, status.Errorf(codes.Internal, "create category tree: %v", err) } category := toProtoCategoryNode(createdParent) - for _, child := range createdChildren { - category.Children = append(category.Children, toProtoCategoryNode(child)) - } return &productv1.CreateCategoryTreeResponse{ Category: category, @@ -608,6 +1210,10 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1. if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } updates, rootIDs, err := categoryTreeUpdatesFromRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) @@ -622,12 +1228,14 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1. } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates)))) defer dbSpan.End() - if err := s.repo.UpdateCategoryTrees(dbCtx, updates); err != nil { + if err := s.repo.UpdateCategoryTrees(dbCtx, updates, scope); err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrCategoryNodeNotFound): return nil, status.Error(codes.NotFound, "category not found") + case errors.Is(err, repository.ErrCategoryNameExists): + return nil, status.Error(codes.AlreadyExists, "category name already exists") case errors.Is(err, repository.ErrCategoryVersionConflict): return nil, status.Error(codes.Aborted, "category version conflict") case errors.Is(err, repository.ErrCategoryTreeConflict): @@ -637,7 +1245,7 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1. return nil, status.Error(codes.Internal, "update category trees") } } - all, err := s.repo.ListCategoryTreeNodes(dbCtx, false) + all, err := s.repo.ListCategoryTreeNodes(dbCtx, false, "", 0, scope) if err != nil { return nil, status.Error(codes.Internal, "load updated category trees") } @@ -656,12 +1264,15 @@ func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1. return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil } -// DeleteCategory removes a single second-level category or a full top-level -// category tree. It never deletes products themselves. +// DeleteCategory removes a category subtree. It never deletes products themselves. func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.DeleteCategoryRequest) (*productv1.DeleteCategoryResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } categoryID, err := normalizeCategoryID(req.GetCategoryId(), "category_id") if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) @@ -671,7 +1282,7 @@ func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.Delet } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category.delete", trace.WithAttributes(attribute.String("category.id", categoryID))) defer dbSpan.End() - result, err := s.repo.DeleteCategory(dbCtx, categoryID, req.GetExpectedVersion()) + result, err := s.repo.DeleteCategory(dbCtx, categoryID, req.GetExpectedVersion(), scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -696,59 +1307,234 @@ func (s *ProductServer) DeleteCategory(ctx context.Context, req *productv1.Delet }, nil } -// CreateGroup creates a top-level product group. +// CreateGroup creates a top-level product group and optional child groups. func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + 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") } - group, err := groupFromCreateRequest(req) + group, children, err := groupTreeFromCreateRequest(req) if err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } group.ID = s.idgen.NextString() + for index := range children { + children[index].ID = s.idgen.NextString() + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create_group", trace.WithAttributes( attribute.String("group.name", group.Name), + attribute.Int("group.child_count", len(children)), )) defer dbSpan.End() - createdGroup, err := s.repo.CreateCategoryNode(dbCtx, group) + createdGroup, createdChildren, err := s.repo.CreateCategoryTree(dbCtx, group, children, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) + if errors.Is(err, repository.ErrGroupNameExists) { + return nil, status.Error(codes.AlreadyExists, "group name already exists") + } s.observer.Logger(ctx).Error("create group failed", zap.String("group_name", group.Name), zap.Error(err)) return nil, status.Errorf(codes.Internal, "create group: %v", err) } - return &productv1.CreateGroupResponse{ - Group: toProtoGroupNode(createdGroup), + protoGroup := toProtoGroupNode(createdGroup) + for _, child := range createdChildren { + protoGroup.Children = append(protoGroup.Children, toProtoGroupNode(child)) + } + return &productv1.CreateGroupResponse{Group: protoGroup}, nil +} + +// CreateGroupChildren batch-creates second-level groups under one first-level group. +func (s *ProductServer) CreateGroupChildren(ctx context.Context, req *productv1.CreateGroupChildrenRequest) (*productv1.CreateGroupChildrenResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + parentID, err := normalizeCategoryID(req.GetGroupId(), "group_id") + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + children, err := groupChildrenFromProto(req.GetChildren()) + 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") + } + for index := range children { + children[index].ID = s.idgen.NextString() + } + created, err := s.repo.CreateGroupChildren(ctx, parentID, children, scope) + if err != nil { + switch { + case errors.Is(err, repository.ErrGroupNameExists): + return nil, status.Error(codes.AlreadyExists, "group name already exists") + case errors.Is(err, repository.ErrInvalidProductGroup), errors.Is(err, repository.ErrCategoryNodeNotFound): + return nil, status.Error(codes.InvalidArgument, "group_id must identify a first-level group") + default: + return nil, status.Errorf(codes.Internal, "create group children: %v", err) + } + } + groups := make([]*productv1.GroupNode, 0, len(created)) + for _, child := range created { + groups = append(groups, toProtoGroupNode(child)) + } + return &productv1.CreateGroupChildrenResponse{Groups: groups}, nil +} + +// UpdateGroup updates mutable fields on one product group. +func (s *ProductServer) UpdateGroup(ctx context.Context, req *productv1.UpdateGroupRequest) (*productv1.UpdateGroupResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + groupID, err := normalizeCategoryID(req.GetGroupId(), "group_id") + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.GetExpectedVersion() < 0 { + return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") + } + update, err := groupFieldUpdateFromRequest(req) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.update", trace.WithAttributes(attribute.String("group.id", groupID))) + defer dbSpan.End() + updated, err := s.repo.UpdateGroup(dbCtx, *update, scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrInvalidProductGroup): + return nil, status.Error(codes.NotFound, "group not found") + case errors.Is(err, repository.ErrCategoryVersionConflict): + return nil, status.Error(codes.Aborted, "group version conflict") + case errors.Is(err, repository.ErrGroupNameExists): + return nil, status.Error(codes.AlreadyExists, "group name already exists") + default: + s.observer.Logger(ctx).Error("update group failed", zap.String("group_id", groupID), zap.Error(err)) + return nil, status.Errorf(codes.Internal, "update group: %v", err) + } + } + return &productv1.UpdateGroupResponse{Group: toProtoGroupNode(updated)}, nil +} + +// DeleteGroup hard-deletes one product group and its bindings. +func (s *ProductServer) DeleteGroup(ctx context.Context, req *productv1.DeleteGroupRequest) (*productv1.DeleteGroupResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "request is required") + } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + groupID, err := normalizeCategoryID(req.GetGroupId(), "group_id") + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.GetExpectedVersion() < 0 { + return nil, status.Error(codes.InvalidArgument, "expected_version must be non-negative") + } + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.delete", trace.WithAttributes(attribute.String("group.id", groupID))) + defer dbSpan.End() + result, err := s.repo.DeleteGroup(dbCtx, groupID, req.GetExpectedVersion(), scope) + if err != nil { + dbSpan.RecordError(err) + dbSpan.SetStatus(otelcodes.Error, err.Error()) + switch { + case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrInvalidProductGroup): + return nil, status.Error(codes.NotFound, "group not found") + case errors.Is(err, repository.ErrCategoryVersionConflict): + return nil, status.Error(codes.Aborted, "group version conflict") + default: + s.observer.Logger(ctx).Error("delete group failed", zap.String("group_id", groupID), zap.Error(err)) + return nil, status.Error(codes.Internal, "delete group") + } + } + return &productv1.DeleteGroupResponse{ + DeletedGroupId: result.DeletedGroupID, + UnboundProductCount: result.UnboundProductCount, + UnboundBindingCount: result.UnboundBindingCount, }, nil } // ListGroups returns product groups. func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroupsRequest) (*productv1.ListGroupsResponse, error) { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } onlyVisible := false + filter := repository.GroupListFilter{} if req != nil { onlyVisible = req.GetOnlyVisible() + filter.FirstLevelName = strings.TrimSpace(req.GetFirstLevelName()) + filter.SecondLevelName = strings.TrimSpace(req.GetSecondLevelName()) + filter.ExactMatch = req.GetExactMatch() } + filter.OnlyVisible = onlyVisible dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.list_groups", trace.WithAttributes( attribute.Bool("group.only_visible", onlyVisible), )) defer dbSpan.End() - groups, err := s.repo.ListGroupNodes(dbCtx, onlyVisible) + page, pageSize := normalizedPage(req.GetPage(), req.GetPageSize()) + groups, total, err := s.repo.ListGroupNodes(dbCtx, filter, page, pageSize, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) - s.observer.Logger(ctx).Error("list groups failed", zap.Bool("only_visible", onlyVisible), zap.Error(err)) + fields := []zap.Field{ + zap.Int64("tenant_id", scope.TenantID), + zap.Int64("store_id", scope.StoreID), + zap.Bool("only_visible", onlyVisible), + zap.String("first_level_name", filter.FirstLevelName), + zap.String("second_level_name", filter.SecondLevelName), + zap.Bool("exact_match", filter.ExactMatch), + zap.Int32("page", page), + zap.Int32("page_size", pageSize), + zap.Error(err), + } + var queryErr *repository.GroupListQueryError + if errors.As(err, &queryErr) { + fields = append(fields, zap.String("sql_query", queryErr.Query), zap.Any("sql_args", queryErr.Args)) + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + fields = append(fields, + zap.String("sqlstate", pgErr.Code), + zap.Int32("sql_position", pgErr.Position), + zap.String("pg_detail", pgErr.Detail), + zap.String("pg_where", pgErr.Where), + zap.String("pg_internal_query", pgErr.InternalQuery), + zap.Int32("pg_internal_position", pgErr.InternalPosition), + ) + } + s.observer.Logger(dbCtx).Error("list groups failed", fields...) return nil, status.Errorf(codes.Internal, "list groups: %v", err) } - dbSpan.SetAttributes(attribute.Int("group.result_count", len(groups))) + dbSpan.SetAttributes( + attribute.Int("group.result_count", len(groups)), + attribute.Int64("group.total", total), + attribute.Int("page", int(page)), + attribute.Int("page_size", int(pageSize)), + ) protoGroups := make([]*productv1.GroupNode, 0, len(groups)) for _, group := range groups { @@ -756,21 +1542,42 @@ func (s *ProductServer) ListGroups(ctx context.Context, req *productv1.ListGroup } return &productv1.ListGroupsResponse{ - Groups: protoGroups, + Groups: protoGroups, + Page: page, + PageSize: pageSize, + Total: total, + TotalPages: totalPages(total, pageSize), }, nil } -// AddProductsToGroup adds one or more products to a category or product group. +// AddProductsToGroup adds one or more products to either a product group or a +// second-level category. Exactly one target id is accepted. func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.AddProductsToGroupRequest) (*productv1.AddProductsToGroupResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + 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") } groupID := strings.TrimSpace(req.GetGroupId()) - if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil { + categoryID := strings.TrimSpace(req.GetCategoryId()) + if (groupID == "" && categoryID == "") || (groupID != "" && categoryID != "") { + return nil, status.Error(codes.InvalidArgument, "exactly one of group_id or category_id is required") + } + targetType := "group" + targetID := groupID + targetField := "group_id" + if categoryID != "" { + targetType = "category" + targetID = categoryID + targetField = "category_id" + } + if err := validatePositiveSnowflakeID(targetID, targetField); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } productIDs, err := normalizeGroupProductIDs(req.GetProductIds()) @@ -783,21 +1590,27 @@ func (s *ProductServer) AddProductsToGroup(ctx context.Context, req *productv1.A bindingIDs[i] = s.idgen.NextString() } - dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.group.add_products", trace.WithAttributes( - attribute.String("group.id", groupID), - attribute.Int("group.product_count", len(productIDs)), + dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_binding.add_products", trace.WithAttributes( + attribute.String("binding.target_type", targetType), + attribute.String("binding.target_id", targetID), + attribute.Int("binding.product_count", len(productIDs)), )) defer dbSpan.End() - if err := s.repo.AddProductsToGroup(dbCtx, groupID, bindingIDs, productIDs); err != nil { + if categoryID != "" { + err = s.repo.AddProductsToCategory(dbCtx, targetID, bindingIDs, productIDs, scope) + } else { + err = s.repo.AddProductsToGroup(dbCtx, targetID, bindingIDs, productIDs, scope) + } + if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) - s.observer.Logger(ctx).Error("add products to group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err)) + s.observer.Logger(ctx).Error("add products to binding target failed", zap.String("target_type", targetType), zap.String("target_id", targetID), zap.Strings("product_ids", productIDs), zap.Error(err)) switch { case errors.Is(err, repository.ErrCategoryNodeNotFound), errors.Is(err, repository.ErrProductNotFound): return nil, status.Error(codes.NotFound, err.Error()) default: - return nil, status.Errorf(codes.Internal, "add products to group: %v", err) + return nil, status.Errorf(codes.Internal, "add products to %s: %v", targetType, err) } } @@ -809,6 +1622,10 @@ func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *produc if req == nil { return nil, status.Error(codes.InvalidArgument, "request is required") } + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } groupID := strings.TrimSpace(req.GetGroupId()) if err := validatePositiveSnowflakeID(groupID, "group_id"); err != nil { @@ -825,7 +1642,7 @@ func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *produc )) defer dbSpan.End() - if err := s.repo.RemoveProductsFromGroup(dbCtx, groupID, productIDs); err != nil { + if err := s.repo.RemoveProductsFromGroup(dbCtx, groupID, productIDs, scope); err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) s.observer.Logger(ctx).Error("remove products from group failed", zap.String("group_id", groupID), zap.Strings("product_ids", productIDs), zap.Error(err)) @@ -840,7 +1657,11 @@ func (s *ProductServer) RemoveProductsFromGroup(ctx context.Context, req *produc // LockInventory reserves sellable stock for a pending order. func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockInventoryRequest) (*productv1.LockInventoryResponse, error) { - if req == nil || req.GetSkuId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetSkuId() == "" { return nil, status.Error(codes.InvalidArgument, "sku_id is required") } if req.GetQuantity() <= 0 { @@ -854,13 +1675,15 @@ func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockIn )) defer dbSpan.End() - inventory, err := s.repo.LockInventory(dbCtx, req.GetSkuId(), req.GetQuantity()) + inventory, err := s.repo.LockInventory(dbCtx, req.GetSkuId(), req.GetQuantity(), scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) switch { case errors.Is(err, repository.ErrSKUNotFound): return nil, status.Error(codes.NotFound, "sku inventory not found") + case errors.Is(err, repository.ErrProductSoldOut): + return nil, status.Error(codes.FailedPrecondition, "product is sold out") case errors.Is(err, repository.ErrProductNotOnSale): return nil, status.Error(codes.FailedPrecondition, "product is not on sale") case errors.Is(err, repository.ErrInsufficientStock): @@ -883,7 +1706,11 @@ func (s *ProductServer) LockInventory(ctx context.Context, req *productv1.LockIn // ConfirmInventory converts locked stock into sold stock for a paid order. func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.ConfirmInventoryRequest) (*productv1.ConfirmInventoryResponse, error) { - if req == nil || req.GetOrderId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetOrderId() == "" { return nil, status.Error(codes.InvalidArgument, "order_id is required") } items, err := toRepositoryInventoryAdjustments(req.GetItems()) @@ -897,7 +1724,7 @@ func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.Con )) defer dbSpan.End() - inventories, err := s.repo.ConfirmInventory(dbCtx, req.GetOrderId(), items) + inventories, err := s.repo.ConfirmInventory(dbCtx, req.GetOrderId(), items, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -908,7 +1735,11 @@ func (s *ProductServer) ConfirmInventory(ctx context.Context, req *productv1.Con // ReleaseInventory releases locked stock for an unpaid closed order. func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.ReleaseInventoryRequest) (*productv1.ReleaseInventoryResponse, error) { - if req == nil || req.GetOrderId() == "" { + scope, err := requireStoreScope(req) + if err != nil { + return nil, err + } + if req.GetOrderId() == "" { return nil, status.Error(codes.InvalidArgument, "order_id is required") } items, err := toRepositoryInventoryAdjustments(req.GetItems()) @@ -922,7 +1753,7 @@ func (s *ProductServer) ReleaseInventory(ctx context.Context, req *productv1.Rel )) defer dbSpan.End() - inventories, err := s.repo.ReleaseInventory(dbCtx, req.GetOrderId(), items) + inventories, err := s.repo.ReleaseInventory(dbCtx, req.GetOrderId(), items, scope) if err != nil { dbSpan.RecordError(err) dbSpan.SetStatus(otelcodes.Error, err.Error()) @@ -994,12 +1825,19 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re } parent := repository.CategoryRecord{ - NodeType: categoryNodeType, - Name: name, - Level: 1, - ImageIDs: imageIDs, - SortNum: req.GetSortNum(), - Status: statusValue, + NodeType: categoryNodeType, + Name: name, + Level: 1, + ImageIDs: imageIDs, + SortNum: req.GetSortNum(), + Status: statusValue, + CampaignID: req.GetCampaignId(), + } + if req.ParentId != nil { + parent.ParentID, err = normalizeCategoryID(req.GetParentId(), "parent_id") + if err != nil { + return repository.CategoryRecord{}, nil, err + } } children := make([]repository.CategoryRecord, 0, len(req.GetChildren())) @@ -1012,10 +1850,10 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re if err != nil { return repository.CategoryRecord{}, nil, err } - if _, exists := childNames[childName]; exists { + if _, exists := childNames[normalizedNodeNameKey(childName)]; exists { return repository.CategoryRecord{}, nil, errors.New("children.name must be unique") } - childNames[childName] = struct{}{} + childNames[normalizedNodeNameKey(childName)] = struct{}{} childImageIDs, err := normalizeNodeImageIDs(child.GetImageJson()) if err != nil { @@ -1026,19 +1864,58 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re return repository.CategoryRecord{}, nil, err } - children = append(children, repository.CategoryRecord{ - NodeType: categoryNodeType, - Name: childName, - Level: 2, - ImageIDs: childImageIDs, - SortNum: child.GetSortNum(), - Status: childStatus, - }) + grandchildren, err := categoryChildrenFromCreateRequest(child.GetChildren(), "children.children") + if err != nil { + return repository.CategoryRecord{}, nil, err + } + children = append(children, repository.CategoryRecord{NodeType: categoryNodeType, Name: childName, ImageIDs: childImageIDs, SortNum: child.GetSortNum(), Status: childStatus, CampaignID: child.GetCampaignId(), Children: grandchildren}) } return parent, children, nil } +func categoryChildrenFromCreateRequest(inputs []*productv1.CreateChildCategory, field string) ([]repository.CategoryRecord, error) { + children := make([]repository.CategoryRecord, 0, len(inputs)) + seen := make(map[string]struct{}, len(inputs)) + for _, child := range inputs { + if child == nil { + return nil, errors.New(field + " item is required") + } + name, err := normalizeNodeName(child.GetName(), field+".name") + if err != nil { + return nil, err + } + if _, exists := seen[normalizedNodeNameKey(name)]; exists { + return nil, errors.New(field + ".name must be unique") + } + seen[normalizedNodeNameKey(name)] = struct{}{} + images, err := normalizeNodeImageIDs(child.GetImageJson()) + if err != nil { + return nil, err + } + statusValue, err := normalizeNodeStatus(child.Status) + if err != nil { + return nil, err + } + grandchildren, err := categoryChildrenFromCreateRequest(child.GetChildren(), field+".children") + if err != nil { + return nil, err + } + children = append(children, repository.CategoryRecord{NodeType: categoryNodeType, Name: name, ImageIDs: images, SortNum: child.GetSortNum(), Status: statusValue, CampaignID: child.GetCampaignId(), Children: grandchildren}) + } + return children, nil +} + +func assignCatalogCategoryIDs(node *repository.CategoryRecord, s *ProductServer) { + if node == nil { + return + } + node.ID = s.idgen.NextString() + for index := range node.Children { + assignCatalogCategoryIDs(&node.Children[index], s) + } +} + func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ([]repository.CategoryTreeUpdate, []string, error) { if len(req.GetCategoryTrees()) == 0 { return nil, nil, errors.New("category_trees is required") @@ -1094,10 +1971,10 @@ func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ( if err != nil { return nil, nil, err } - if _, exists := newChildNames[newChild.Name]; exists { + if _, exists := newChildNames[normalizedNodeNameKey(newChild.Name)]; exists { return nil, nil, errors.New("new_child_categories.name must be unique") } - newChildNames[newChild.Name] = struct{}{} + newChildNames[normalizedNodeNameKey(newChild.Name)] = struct{}{} update.NewChildren = append(update.NewChildren, newChild) } if update.Category == nil && len(update.Children) == 0 && len(update.NewChildren) == 0 { @@ -1126,11 +2003,12 @@ func newChildCategoryFromProto(child *productv1.CreateChildCategory) (repository return repository.CategoryRecord{}, err } return repository.CategoryRecord{ - NodeType: categoryNodeType, - Name: name, - ImageIDs: imageIDs, - SortNum: child.GetSortNum(), - Status: statusValue, + NodeType: categoryNodeType, + Name: name, + ImageIDs: imageIDs, + SortNum: child.GetSortNum(), + Status: statusValue, + CampaignID: child.GetCampaignId(), }, nil } @@ -1166,6 +2044,14 @@ func categoryFieldUpdateFromProto(id string, patch *productv1.CategoryFieldPatch return nil, fmt.Errorf("%s.status must be 0 or 1", field) } update.Status = &value + case "campaign_id": + value := strings.TrimSpace(patch.GetCampaignId()) + if value != "" { + if _, err := normalizeCategoryID(value, field+".campaign_id"); err != nil { + return nil, err + } + } + update.CampaignID = &value } } return update, nil @@ -1175,7 +2061,7 @@ func categoryUpdatePaths(mask *fieldmaskpb.FieldMask) ([]string, error) { if mask == nil || len(mask.GetPaths()) == 0 { return nil, errors.New("update_mask is required") } - allowed := map[string]struct{}{"name": {}, "image_ids": {}, "sort_num": {}, "status": {}} + allowed := map[string]struct{}{"name": {}, "image_ids": {}, "sort_num": {}, "status": {}, "campaign_id": {}} paths := make([]string, 0, len(mask.GetPaths())) seen := make(map[string]struct{}, len(mask.GetPaths())) for _, path := range mask.GetPaths() { @@ -1200,32 +2086,128 @@ func normalizeCategoryID(value, field string) (string, error) { return trimmed, nil } -func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, error) { +func groupTreeFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, []repository.CategoryRecord, error) { name, err := normalizeNodeName(req.GetName(), "name") if err != nil { - return repository.CategoryRecord{}, err + return repository.CategoryRecord{}, nil, err } imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) if err != nil { - return repository.CategoryRecord{}, err + return repository.CategoryRecord{}, nil, err } statusValue, err := normalizeNodeStatus(req.Status) if err != nil { - return repository.CategoryRecord{}, err + return repository.CategoryRecord{}, nil, err } - - return repository.CategoryRecord{ + parent := repository.CategoryRecord{ NodeType: groupNodeType, Name: name, Level: 1, ImageIDs: imageIDs, SortNum: req.GetSortNum(), Status: statusValue, - }, nil + } + children, err := groupChildrenFromProto(req.GetChildren()) + if err != nil { + return repository.CategoryRecord{}, nil, err + } + return parent, children, nil +} + +func groupChildrenFromProto(items []*productv1.CreateChildGroup) ([]repository.CategoryRecord, error) { + if len(items) > 100 { + return nil, errors.New("children must contain at most 100 items") + } + children := make([]repository.CategoryRecord, 0, len(items)) + names := make(map[string]struct{}, len(items)) + for _, item := range items { + if item == nil { + return nil, errors.New("children item is required") + } + name, err := normalizeNodeName(item.GetName(), "children.name") + if err != nil { + return nil, err + } + if _, exists := names[normalizedNodeNameKey(name)]; exists { + return nil, errors.New("children.name must be unique") + } + names[normalizedNodeNameKey(name)] = struct{}{} + imageIDs, err := normalizeNodeImageIDs(item.GetImageJson()) + if err != nil { + return nil, err + } + statusValue, err := normalizeNodeStatus(item.Status) + if err != nil { + return nil, err + } + children = append(children, repository.CategoryRecord{NodeType: groupNodeType, Name: name, Level: 2, ImageIDs: imageIDs, SortNum: item.GetSortNum(), Status: statusValue}) + } + return children, nil +} + +func groupFieldUpdateFromRequest(req *productv1.UpdateGroupRequest) (*repository.CategoryFieldUpdate, error) { + if req.GetUpdateMask() == nil || len(req.GetUpdateMask().GetPaths()) == 0 { + return nil, errors.New("update_mask is required") + } + update := &repository.CategoryFieldUpdate{ + ID: strings.TrimSpace(req.GetGroupId()), + ExpectedVersion: req.GetExpectedVersion(), + } + seen := make(map[string]struct{}, len(req.GetUpdateMask().GetPaths())) + for _, path := range req.GetUpdateMask().GetPaths() { + path = strings.TrimSpace(path) + if path == "" { + continue + } + if _, dup := seen[path]; dup { + return nil, fmt.Errorf("duplicate update path %q", path) + } + seen[path] = struct{}{} + switch path { + case "name": + if req.Name == nil { + return nil, errors.New("name is required when present in update_mask") + } + value, err := normalizeNodeName(*req.Name, "name") + if err != nil { + return nil, err + } + update.Name = &value + case "image_json", "image_ids": + raw := "" + if req.ImageJson != nil { + raw = *req.ImageJson + } + imageIDs, err := normalizeNodeImageIDs(raw) + if err != nil { + return nil, err + } + update.ImageIDs = &imageIDs + case "sort_num": + if req.SortNum == nil { + return nil, errors.New("sort_num is required when present in update_mask") + } + update.SortNum = req.SortNum + case "status": + if req.Status == nil { + return nil, errors.New("status is required when present in update_mask") + } + if *req.Status != 0 && *req.Status != 1 { + return nil, errors.New("status must be 0 or 1") + } + update.Status = req.Status + default: + return nil, fmt.Errorf("unsupported update path %q", path) + } + } + if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil { + return nil, errors.New("at least one mutable field is required") + } + return update, nil } func normalizeNodeName(raw, field string) (string, error) { - name := strings.TrimSpace(raw) + name := strings.Join(strings.Fields(raw), " ") if name == "" { return "", fmt.Errorf("%s is required", field) } @@ -1235,6 +2217,10 @@ func normalizeNodeName(raw, field string) (string, error) { return name, nil } +func normalizedNodeNameKey(name string) string { + return strings.ToLower(name) +} + func normalizeNodeImageIDs(raw string) ([]string, error) { raw = strings.TrimSpace(raw) if raw == "" { @@ -1259,9 +2245,6 @@ func normalizeNodeStatus(statusValue *int32) (int32, error) { func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.ProductRecord, []repository.SKURecord, error) { spuNo := strings.TrimSpace(req.GetSpuNo()) - if spuNo == "" { - return repository.ProductRecord{}, nil, errors.New("spu_no is required") - } title := strings.TrimSpace(req.GetTitle()) if title == "" { @@ -1274,38 +2257,69 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P } if statusValue != productv1.ProductStatus_PRODUCT_STATUS_INVENTORY && statusValue != productv1.ProductStatus_PRODUCT_STATUS_ON_SALE && - statusValue != productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE { + statusValue != productv1.ProductStatus_PRODUCT_STATUS_SOLD_OUT { return repository.ProductRecord{}, nil, errors.New("unsupported product status") } crossBorderJSON, err := crossBorderJSONFromProto(req.GetCrossBorderInfo()) if err != nil { return repository.ProductRecord{}, nil, err } + categoryPropertiesJSON, err := categoryPropertiesJSONFromProto(req.GetCategoryProperties()) + if err != nil { + return repository.ProductRecord{}, nil, err + } + distributionProductDetailJSON, err := normalizeDistributionProductDetailJSON(req.GetDistributionProductDetail()) + if err != nil { + return repository.ProductRecord{}, nil, err + } record := repository.ProductRecord{ - SPUNo: spuNo, - Title: title, - SellingPoint: strings.TrimSpace(req.GetSellingPoint()), - BrandID: strings.TrimSpace(req.GetBrandId()), - SupplierID: strings.TrimSpace(req.GetSupplierId()), - ImageIDs: normalizeStringList(req.GetImageIds()), - DetailHTML: req.GetDetailHtml(), - MemberDiscountEnabled: req.GetMemberDiscountEnabled(), - GoodsType: defaultInt32(req.GetGoodsType(), 1), - ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()), - Status: statusValue, - CrossBorderJSON: crossBorderJSON, - FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1), - FreightFixedAmount: req.GetFreightFixedAmount(), - FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), - SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), - ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), + SPUNo: spuNo, + Title: title, + SellingPoint: strings.TrimSpace(req.GetSellingPoint()), + BrandID: strings.TrimSpace(req.GetBrandId()), + SupplierID: strings.TrimSpace(req.GetSupplierId()), + ImageIDs: normalizeStringList(req.GetImageIds()), + DetailHTML: "", + MemberDiscountEnabled: req.GetMemberDiscountEnabled(), + GoodsType: defaultInt32(req.GetGoodsType(), 1), + ServiceGuarantees: normalizeStringList(req.GetServiceGuarantees()), + Status: statusValue, + CrossBorderJSON: crossBorderJSON, + CategoryPropertiesJSON: categoryPropertiesJSON, + FreightChargeType: defaultInt32(req.GetFreightChargeType(), 1), + FreightFixedAmount: req.GetFreightFixedAmount(), + FreightTemplateID: strings.TrimSpace(req.GetFreightTemplateId()), + SaleTimeType: defaultInt32(req.GetSaleTimeType(), 1), + ScheduledSaleTime: timestampToTime(req.GetScheduledSaleTime()), + PresaleType: req.GetPresaleType(), + DeliveryTimeType: req.GetDeliveryTimeType(), + DeliveryStartAt: timestampToTime(req.GetDeliveryStartAt()), + DeliveryAfterPaidDays: req.GetDeliveryAfterPaidDays(), + PurchaseLimitQuantity: req.GetPurchaseLimitQuantity(), + IsDistributionProduct: req.GetIsDistributionProduct(), + DistributionProductDetailJSON: distributionProductDetailJSON, } - leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCategoryIds()) + detailHTML, err := sanitizeDetailHTML(req.GetDetailHtml()) + if err != nil { + return repository.ProductRecord{}, nil, err + } + record.DetailHTML = detailHTML + leafCategoryIDs, err := normalizeLeafCategoryIDs(req.GetLeafCatalogCategoryIds()) if err != nil { return repository.ProductRecord{}, nil, err } record.LeafCategoryIDs = leafCategoryIDs + groupIDs, err := normalizeGroupIDs(req.GetGroupIds()) + if err != nil { + return repository.ProductRecord{}, nil, err + } + record.GroupIDs = groupIDs + productCategoryIDs, err := normalizeProductCategoryIDs(req.GetProductCategoryIds()) + if err != nil { + return repository.ProductRecord{}, nil, err + } + record.ProductCategoryIDs = productCategoryIDs if record.FreightFixedAmount < 0 { return repository.ProductRecord{}, nil, errors.New("freight_fixed_amount must be greater than or equal to 0") } @@ -1324,6 +2338,9 @@ func productFromCreateRequest(req *productv1.CreateProductRequest) (repository.P if record.SaleTimeType == 2 && record.ScheduledSaleTime == nil { return repository.ProductRecord{}, nil, errors.New("scheduled_sale_time is required when sale_time_type is 2") } + if err := validateProductDeliveryConfiguration(&record); err != nil { + return repository.ProductRecord{}, nil, err + } skus := make([]repository.SKURecord, 0, len(req.GetSkus())) for i, protoSKU := range req.GetSkus() { @@ -1364,7 +2381,11 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro case "image_ids": merged.ImageIDs = normalizeStringList(update.GetImageIds()) case "detail_html": - merged.DetailHTML = update.GetDetailHtml() + sanitized, err := sanitizeDetailHTML(update.GetDetailHtml()) + if err != nil { + return repository.ProductRecord{}, err + } + merged.DetailHTML = sanitized case "member_discount_enabled": merged.MemberDiscountEnabled = update.GetMemberDiscountEnabled() case "service_guarantees": @@ -1375,6 +2396,12 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro return repository.ProductRecord{}, err } merged.CrossBorderJSON = crossBorderJSON + case "category_properties": + categoryPropertiesJSON, err := categoryPropertiesJSONFromProto(update.GetCategoryProperties()) + if err != nil { + return repository.ProductRecord{}, err + } + merged.CategoryPropertiesJSON = categoryPropertiesJSON case "freight_charge_type": merged.FreightChargeType = update.GetFreightChargeType() case "freight_fixed_amount": @@ -1387,12 +2414,42 @@ func mergeProductUpdate(current *repository.ProductRecord, update *productv1.Pro merged.ScheduledSaleTime = timestampToTime(update.GetScheduledSaleTime()) case "goods_type": merged.GoodsType = update.GetGoodsType() - case "leaf_category_ids": - leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCategoryIds()) + case "presale_type": + merged.PresaleType = update.GetPresaleType() + case "delivery_time_type": + merged.DeliveryTimeType = update.GetDeliveryTimeType() + case "delivery_start_at": + merged.DeliveryStartAt = timestampToTime(update.GetDeliveryStartAt()) + case "delivery_after_paid_days": + merged.DeliveryAfterPaidDays = update.GetDeliveryAfterPaidDays() + case "purchase_limit_quantity": + merged.PurchaseLimitQuantity = update.GetPurchaseLimitQuantity() + case "is_distribution_product": + merged.IsDistributionProduct = update.GetIsDistributionProduct() + case "distribution_product_detail": + detailJSON, err := normalizeDistributionProductDetailJSON(update.GetDistributionProductDetail()) + if err != nil { + return repository.ProductRecord{}, err + } + merged.DistributionProductDetailJSON = detailJSON + case "leaf_catalog_category_ids": + leafCategoryIDs, err := normalizeLeafCategoryIDs(update.GetLeafCatalogCategoryIds()) if err != nil { return repository.ProductRecord{}, err } merged.LeafCategoryIDs = leafCategoryIDs + case "group_ids": + groupIDs, err := normalizeGroupIDs(update.GetGroupIds()) + if err != nil { + return repository.ProductRecord{}, err + } + merged.GroupIDs = groupIDs + case "product_category_ids": + productCategoryIDs, err := normalizeProductCategoryIDs(update.GetProductCategoryIds()) + if err != nil { + return repository.ProductRecord{}, err + } + merged.ProductCategoryIDs = productCategoryIDs default: return repository.ProductRecord{}, fmt.Errorf("unsupported update field %q", path) } @@ -1409,7 +2466,48 @@ func containsUpdatePath(paths []string, target string) bool { return false } -func validateProductForUpdate(product repository.ProductRecord) error { +func productFreightChargeFromUpdateRequest(req *productv1.UpdateProductFreightChargeRequest) (spuNo string, freightChargeType int32, freightFixedAmount int64, freightTemplateID string, err error) { + spuNo = strings.TrimSpace(req.GetSpuNo()) + if spuNo == "" { + return "", 0, 0, "", errors.New("spu_no is required") + } + if utf8.RuneCountInString(spuNo) > 100 { + return "", 0, 0, "", errors.New("spu_no must contain at most 100 characters") + } + freightChargeType = req.GetFreightChargeType() + switch freightChargeType { + case 1: + if req.FreightFixedAmount == nil { + return "", 0, 0, "", errors.New("freight_fixed_amount is required when freight_charge_type is 1") + } + if *req.FreightFixedAmount < 0 { + return "", 0, 0, "", errors.New("freight_fixed_amount must be greater than or equal to 0") + } + if req.FreightTemplateId != nil { + return "", 0, 0, "", errors.New("freight_template_id must be omitted when freight_charge_type is 1") + } + return spuNo, freightChargeType, *req.FreightFixedAmount, "", nil + case 2: + if req.FreightFixedAmount != nil { + return "", 0, 0, "", errors.New("freight_fixed_amount must be omitted when freight_charge_type is 2") + } + if req.FreightTemplateId == nil { + return "", 0, 0, "", errors.New("freight_template_id is required when freight_charge_type is 2") + } + freightTemplateID = strings.TrimSpace(*req.FreightTemplateId) + if freightTemplateID == "" { + return "", 0, 0, "", errors.New("freight_template_id is required when freight_charge_type is 2") + } + return spuNo, freightChargeType, 0, freightTemplateID, nil + default: + return "", 0, 0, "", errors.New("freight_charge_type must be 1 or 2") + } +} + +func validateProductForUpdate(product *repository.ProductRecord) error { + if product == nil { + return errors.New("product is required") + } if strings.TrimSpace(product.Title) == "" { return errors.New("title is required") } @@ -1431,6 +2529,33 @@ func validateProductForUpdate(product repository.ProductRecord) error { if product.SaleTimeType == 2 && product.ScheduledSaleTime == nil { return errors.New("scheduled_sale_time is required when sale_time_type is 2") } + return validateProductDeliveryConfiguration(product) +} + +func validateProductDeliveryConfiguration(product *repository.ProductRecord) error { + if product.PresaleType < 0 || product.PresaleType > 2 { + return errors.New("presale_type must be 0, 1, or 2") + } + if product.PurchaseLimitQuantity < 0 { + return errors.New("purchase_limit_quantity must be greater than or equal to 0") + } + switch product.DeliveryTimeType { + case 0: + product.DeliveryStartAt = nil + product.DeliveryAfterPaidDays = 0 + case 1: + if product.DeliveryStartAt == nil { + return errors.New("delivery_start_at is required when delivery_time_type is 1") + } + product.DeliveryAfterPaidDays = 0 + case 2: + if product.DeliveryAfterPaidDays <= 0 { + return errors.New("delivery_after_paid_days must be greater than 0 when delivery_time_type is 2") + } + product.DeliveryStartAt = nil + default: + return errors.New("delivery_time_type must be 0, 1, or 2") + } return nil } @@ -1498,6 +2623,18 @@ func skuUpdateFromProto(input *productv1.PatchExistingSKU) (repository.SKUUpdate case "price": value := input.GetPrice() update.Price = &value + case "supply_price": + update.SupplyPriceSet = true + update.SupplyPrice = input.SupplyPrice + case "weight_kg": + update.WeightKgSet = true + update.WeightKg = input.WeightKg + if update.WeightKg != nil && *update.WeightKg < 0 { + return repository.SKUUpdate{}, errors.New("weight_kg must be greater than or equal to 0") + } + case "barcode": + value := strings.TrimSpace(input.GetBarcode()) + update.Barcode = &value case "stock_quantity": value := input.GetStockQuantity() update.StockQuantity = &value @@ -1550,6 +2687,12 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, if sku.GetPrice() < 0 { return repository.SKURecord{}, errors.New("price must be greater than or equal to 0") } + if sku.SupplyPrice != nil && *sku.SupplyPrice < 0 { + return repository.SKURecord{}, errors.New("supply_price must be greater than or equal to 0") + } + if sku.WeightKg != nil && *sku.WeightKg < 0 { + return repository.SKURecord{}, errors.New("weight_kg must be greater than or equal to 0") + } if sku.GetStockQuantity() < 0 { return repository.SKURecord{}, errors.New("stock_quantity must be greater than or equal to 0") } @@ -1571,6 +2714,9 @@ func skuFromCreateInput(sku *productv1.CreateProductSKU) (repository.SKURecord, SKUNo: strings.TrimSpace(sku.GetSkuNo()), Name: name, Price: sku.GetPrice(), + SupplyPrice: sku.SupplyPrice, + WeightKg: sku.WeightKg, + Barcode: strings.TrimSpace(sku.GetBarcode()), ImageIDs: normalizeStringList(sku.GetImageIds()), StockQuantity: sku.GetStockQuantity(), AttributesJSON: attrs, @@ -1662,6 +2808,42 @@ func toProtoCrossBorderInfo(raw string) *productv1.CrossBorderInfo { return info } +func categoryPropertiesJSONFromProto(properties *structpb.Struct) (string, error) { + if properties == nil { + return "{}", nil + } + raw, err := json.Marshal(properties.AsMap()) + if err != nil { + return "", fmt.Errorf("marshal category_properties: %w", err) + } + return string(raw), nil +} + +func normalizeDistributionProductDetailJSON(raw string) (string, error) { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + return "{}", nil + } + if !json.Valid([]byte(trimmed)) { + return "", errors.New("distribution_product_detail must be valid JSON") + } + return trimmed, nil +} + +func categoryPropertiesProto(raw string) *structpb.Struct { + properties := make(map[string]any) + if strings.TrimSpace(raw) != "" { + if err := json.Unmarshal([]byte(raw), &properties); err != nil || properties == nil { + return &structpb.Struct{Fields: map[string]*structpb.Value{}} + } + } + result, err := structpb.NewStruct(properties) + if err != nil { + return &structpb.Struct{Fields: map[string]*structpb.Value{}} + } + return result +} + func normalizeStringList(values []string) []string { if len(values) == 0 { return []string{} @@ -1684,20 +2866,20 @@ func normalizeStringList(values []string) []string { func normalizeLeafCategoryIDs(values []string) ([]string, error) { if len(values) > 100 { - return nil, errors.New("leaf_category_ids must contain at most 100 items") + return nil, errors.New("leaf_catalog_category_ids must contain at most 100 items") } leafCategoryIDs := make([]string, 0, len(values)) seen := make(map[string]struct{}, len(values)) for _, value := range values { categoryID := strings.TrimSpace(value) if categoryID == "" { - return nil, errors.New("leaf_category_ids must not contain an empty id") + return nil, errors.New("leaf_catalog_category_ids must not contain an empty id") } - if _, err := normalizeCategoryID(categoryID, "leaf_category_ids"); err != nil { + if _, err := normalizeCategoryID(categoryID, "leaf_catalog_category_ids"); err != nil { return nil, err } if _, duplicate := seen[categoryID]; duplicate { - return nil, errors.New("leaf_category_ids must not contain duplicates") + return nil, errors.New("leaf_catalog_category_ids must not contain duplicates") } seen[categoryID] = struct{}{} leafCategoryIDs = append(leafCategoryIDs, categoryID) @@ -1705,6 +2887,52 @@ func normalizeLeafCategoryIDs(values []string) ([]string, error) { return leafCategoryIDs, nil } +func normalizeGroupIDs(values []string) ([]string, error) { + if len(values) > 100 { + return nil, errors.New("group_ids must contain at most 100 items") + } + groupIDs := make([]string, 0, len(values)) + seen := make(map[string]struct{}, len(values)) + for _, value := range values { + groupID := strings.TrimSpace(value) + if groupID == "" { + return nil, errors.New("group_ids must not contain an empty id") + } + if _, err := normalizeCategoryID(groupID, "group_ids"); err != nil { + return nil, err + } + if _, duplicate := seen[groupID]; duplicate { + return nil, errors.New("group_ids must not contain duplicates") + } + seen[groupID] = struct{}{} + groupIDs = append(groupIDs, groupID) + } + return groupIDs, nil +} + +func normalizeProductCategoryIDs(values []string) ([]string, error) { + if len(values) > 100 { + return nil, errors.New("product_category_ids must contain at most 100 items") + } + categoryIDs := make([]string, 0, len(values)) + seen := make(map[string]struct{}, len(values)) + for _, value := range values { + categoryID := strings.TrimSpace(value) + if categoryID == "" { + return nil, errors.New("product_category_ids must not contain an empty id") + } + if _, err := normalizeCategoryID(categoryID, "product_category_ids"); err != nil { + return nil, err + } + if _, duplicate := seen[categoryID]; duplicate { + return nil, errors.New("product_category_ids must not contain duplicates") + } + seen[categoryID] = struct{}{} + categoryIDs = append(categoryIDs, categoryID) + } + return categoryIDs, nil +} + func normalizeGroupProductIDs(values []string) ([]string, error) { productIDs := normalizeStringList(values) if len(productIDs) == 0 { @@ -1759,6 +2987,13 @@ func timePtrToMillisString(value *time.Time) *string { return &millis } +func timePtrToTimestamp(value *time.Time) *timestamppb.Timestamp { + if value == nil { + return nil + } + return timestamppb.New(*value) +} + func validatePositiveID(raw, field string) error { if raw == "" { return errors.New(field + " is required") @@ -1783,6 +3018,9 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco SkuNo: sku.SKUNo, Name: sku.Name, Price: sku.Price, + SupplyPrice: sku.SupplyPrice, + WeightKg: sku.WeightKg, + Barcode: sku.Barcode, StockQuantity: sku.StockQuantity, SoldQuantity: sku.SoldQuantity, AttributesJson: sku.AttributesJSON, @@ -1804,33 +3042,63 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco }) } - return &productv1.Product{ - ProductId: product.ID, - SpuNo: product.SPUNo, - Title: product.Title, - SellingPoint: product.SellingPoint, - Status: product.Status, - Skus: protoSKUs, - CreatedAt: timeToMillisString(product.CreatedAt), - UpdatedAt: timeToMillisString(product.UpdatedAt), - ImageIds: product.ImageIDs, - BrandId: product.BrandID, - SupplierId: product.SupplierID, - DetailHtml: product.DetailHTML, - MemberDiscountEnabled: product.MemberDiscountEnabled, - GoodsType: product.GoodsType, - ServiceGuarantees: product.ServiceGuarantees, - CrossBorderJson: product.CrossBorderJSON, - CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), - FreightChargeType: product.FreightChargeType, - FreightFixedAmount: product.FreightFixedAmount, - FreightTemplateId: product.FreightTemplateID, - SaleTimeType: product.SaleTimeType, - ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), - Version: product.Version, - DeletedAt: timePtrToMillisString(product.DeletedAt), - LeafCategoryIds: append([]string(nil), product.LeafCategoryIDs...), + result := &productv1.Product{ + ProductId: product.ID, + SpuNo: product.SPUNo, + Title: product.Title, + SellingPoint: product.SellingPoint, + Status: product.Status, + Skus: protoSKUs, + CreatedAt: timeToMillisString(product.CreatedAt), + UpdatedAt: timeToMillisString(product.UpdatedAt), + ImageIds: product.ImageIDs, + BrandId: product.BrandID, + SupplierId: product.SupplierID, + DetailHtml: product.DetailHTML, + MemberDiscountEnabled: product.MemberDiscountEnabled, + GoodsType: product.GoodsType, + ServiceGuarantees: product.ServiceGuarantees, + CrossBorderJson: product.CrossBorderJSON, + CrossBorderInfo: toProtoCrossBorderInfo(product.CrossBorderJSON), + CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON), + FreightChargeType: product.FreightChargeType, + FreightFixedAmount: product.FreightFixedAmount, + FreightTemplateId: product.FreightTemplateID, + SaleTimeType: product.SaleTimeType, + ScheduledSaleTime: timePtrToMillisString(product.ScheduledSaleTime), + PresaleType: product.PresaleType, + DeliveryTimeType: product.DeliveryTimeType, + DeliveryStartAt: timePtrToTimestamp(product.DeliveryStartAt), + DeliveryAfterPaidDays: product.DeliveryAfterPaidDays, + PurchaseLimitQuantity: product.PurchaseLimitQuantity, + IsDistributionProduct: product.IsDistributionProduct, + DistributionProductDetail: product.DistributionProductDetailJSON, + Version: product.Version, + DeletedAt: timePtrToMillisString(product.DeletedAt), + LeafCatalogCategoryIds: append([]string(nil), product.LeafCategoryIDs...), + GroupIds: append([]string(nil), product.GroupIDs...), + ProductCategoryIds: append([]string(nil), product.ProductCategoryIDs...), } + for _, category := range product.ProductCategories { + item := &productv1.ProductCategorySummary{ + ProductCategoryId: category.ID, + Name: category.Name, + Level: category.Level, + ParentCategoryId: category.ParentID, + ParentCategoryName: category.ParentName, + Path: make([]*productv1.ProductCategoryPathNode, 0, len(category.Path)), + } + for _, node := range category.Path { + item.Path = append(item.Path, &productv1.ProductCategoryPathNode{ + ProductCategoryId: node.ID, + Name: node.Name, + Level: node.Level, + ParentCategoryId: node.ParentID, + }) + } + result.ProductCategories = append(result.ProductCategories, item) + } + return result } func toProtoCartItemProduct(lineID string, record repository.CartItemProductRecord) *productv1.CartItemProduct { @@ -1848,6 +3116,11 @@ func toProtoCartItemProduct(lineID string, record repository.CartItemProductReco result.ServiceGuarantees = record.Product.ServiceGuarantees result.SpuImageIds = record.Product.ImageIDs result.SpuStatus = record.Product.Status + result.PresaleType = record.Product.PresaleType + result.DeliveryTimeType = record.Product.DeliveryTimeType + result.DeliveryStartAt = timePtrToTimestamp(record.Product.DeliveryStartAt) + result.DeliveryAfterPaidDays = record.Product.DeliveryAfterPaidDays + result.PurchaseLimitQuantity = record.Product.PurchaseLimitQuantity if record.SKU == nil { return result } @@ -1866,19 +3139,50 @@ func toProtoCategoryProduct(product *repository.CategoryProductRecord) *productv if product == nil { return nil } - return &productv1.CategoryProduct{ - UpdatedAt: timeToMillisString(product.UpdatedAt), - CreatedAt: timeToMillisString(product.CreatedAt), - Title: product.Title, - ProductId: product.ID, - SpuNo: product.SPUNo, - Status: product.Status, - ImageIds: product.ImageIDs, - Price: product.Price, - SoldQuantity: product.SoldQuantity, - StockQuantity: product.StockQuantity, - LockedQuantity: product.LockedQuantity, + result := &productv1.CategoryProduct{ + UpdatedAt: timeToMillisString(product.UpdatedAt), + CreatedAt: timeToMillisString(product.CreatedAt), + Title: product.Title, + ProductId: product.ID, + SpuNo: product.SPUNo, + Status: product.Status, + ImageIds: product.ImageIDs, + Price: product.Price, + SoldQuantity: product.SoldQuantity, + StockQuantity: product.StockQuantity, + LockedQuantity: product.LockedQuantity, + CategoryProperties: categoryPropertiesProto(product.CategoryPropertiesJSON), + PresaleType: product.PresaleType, + IsDistributionProduct: product.IsDistributionProduct, } + for _, category := range product.ProductCategories { + item := &productv1.ProductCategorySummary{ + ProductCategoryId: category.ID, + Name: category.Name, + Level: category.Level, + ParentCategoryId: category.ParentID, + ParentCategoryName: category.ParentName, + Path: make([]*productv1.ProductCategoryPathNode, 0, len(category.Path)), + } + for _, node := range category.Path { + item.Path = append(item.Path, &productv1.ProductCategoryPathNode{ + ProductCategoryId: node.ID, + Name: node.Name, + Level: node.Level, + ParentCategoryId: node.ParentID, + }) + } + result.ProductCategories = append(result.ProductCategories, item) + } + for _, group := range product.Groups { + result.Groups = append(result.Groups, &productv1.ProductGroupSummary{GroupId: group.ID, Name: group.Name}) + } + if product.Brand != nil { + result.Brand = &productv1.ProductBrandSummary{ + BrandId: product.Brand.ID, Name: product.Brand.Name, Alias: product.Brand.Alias, BrandCode: product.Brand.BrandCode, + } + } + return result } func toProtoInventory(inventory *repository.InventoryRecord) *productv1.ProductItemInventory { @@ -1945,7 +3249,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor if category == nil { return nil } - return &productv1.CategoryNode{ + out := &productv1.CategoryNode{ CategoryId: category.ID, NodeType: category.NodeType, Name: category.Name, @@ -1954,25 +3258,51 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor ImageJson: categoryImageIDsJSON(category.ImageIDs), SortNum: category.SortNum, Status: category.Status, + CampaignId: category.CampaignID, Version: category.Version, Children: []*productv1.CategoryNode{}, } + for index := range category.Children { + out.Children = append(out.Children, toProtoCategoryNode(&category.Children[index])) + } + return out } func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode { if group == nil { return nil } - return &productv1.GroupNode{ - GroupId: group.ID, - NodeType: group.NodeType, - Name: group.Name, - ParentId: group.ParentID, - Level: group.Level, - ImageJson: categoryImageIDsJSON(group.ImageIDs), - SortNum: group.SortNum, - Status: group.Status, + node := &productv1.GroupNode{ + GroupId: group.ID, + NodeType: group.NodeType, + Name: group.Name, + ParentId: group.ParentID, + Level: group.Level, + ImageJson: categoryImageIDsJSON(group.ImageIDs), + SortNum: group.SortNum, + Status: group.Status, + ProductCount: group.ProductCount, + IsLeaf: group.IsLeaf, + Version: group.Version, } + if group.IsLeaf { + node.Brands = make([]*productv1.GroupBrandProductSummary, 0, len(group.BrandProducts)) + for _, brand := range group.BrandProducts { + node.Brands = append(node.Brands, &productv1.GroupBrandProductSummary{ + BrandId: brand.BrandID, + BrandName: brand.BrandName, + }) + protoBrand := node.Brands[len(node.Brands)-1] + protoBrand.Products = make([]*productv1.GroupBrandProduct, 0, len(brand.Products)) + for _, product := range brand.Products { + protoBrand.Products = append(protoBrand.Products, &productv1.GroupBrandProduct{ + ProductId: product.ProductID, + SpuNo: product.SPUNo, + }) + } + } + } + return node } func categoryImageIDsJSON(imageIDs []string) string { diff --git a/internal/server/scheduled_sale_worker.go b/internal/server/scheduled_sale_worker.go new file mode 100644 index 0000000..88aeb98 --- /dev/null +++ b/internal/server/scheduled_sale_worker.go @@ -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() + } + } + }() +} diff --git a/internal/server/store_scope.go b/internal/server/store_scope.go new file mode 100644 index 0000000..69f3567 --- /dev/null +++ b/internal/server/store_scope.go @@ -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 +} diff --git a/internal/server/store_scope_test.go b/internal/server/store_scope_test.go new file mode 100644 index 0000000..9723128 --- /dev/null +++ b/internal/server/store_scope_test.go @@ -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") + } +} diff --git a/scripts/sql/006_rebuild_standard_product_category_tree.sql b/scripts/sql/006_rebuild_standard_product_category_tree.sql new file mode 100644 index 0000000..6e202be --- /dev/null +++ b/scripts/sql/006_rebuild_standard_product_category_tree.sql @@ -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; diff --git a/scripts/sql/007_catalog_category_multilevel_tree.sql b/scripts/sql/007_catalog_category_multilevel_tree.sql new file mode 100644 index 0000000..0394c79 --- /dev/null +++ b/scripts/sql/007_catalog_category_multilevel_tree.sql @@ -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.'; diff --git a/scripts/sql/008_product_presale_delivery_purchase_limit.sql b/scripts/sql/008_product_presale_delivery_purchase_limit.sql new file mode 100644 index 0000000..af8e529 --- /dev/null +++ b/scripts/sql/008_product_presale_delivery_purchase_limit.sql @@ -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; diff --git a/scripts/sql/009_catalog_category_created_at.sql b/scripts/sql/009_catalog_category_created_at.sql new file mode 100644 index 0000000..ff61028 --- /dev/null +++ b/scripts/sql/009_catalog_category_created_at.sql @@ -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); diff --git a/scripts/sql/010_catalog_category_binding_audit_fields.sql b/scripts/sql/010_catalog_category_binding_audit_fields.sql new file mode 100644 index 0000000..c92dc98 --- /dev/null +++ b/scripts/sql/010_catalog_category_binding_audit_fields.sql @@ -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; diff --git a/scripts/sql/011_add_products_is_distribution_product.sql b/scripts/sql/011_add_products_is_distribution_product.sql new file mode 100644 index 0000000..8ac311f --- /dev/null +++ b/scripts/sql/011_add_products_is_distribution_product.sql @@ -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 表示非分销商品'; diff --git a/scripts/sql/012_add_products_distribution_product_detail.sql b/scripts/sql/012_add_products_distribution_product_detail.sql new file mode 100644 index 0000000..ea8e1a7 --- /dev/null +++ b/scripts/sql/012_add_products_distribution_product_detail.sql @@ -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'; diff --git a/scripts/sql/02-product-schema.sql b/scripts/sql/02-product-schema.sql new file mode 100644 index 0000000..84e6dd9 --- /dev/null +++ b/scripts/sql/02-product-schema.sql @@ -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; diff --git a/scripts/sql/add-product-item-supply-price.sql b/scripts/sql/add-product-item-supply-price.sql new file mode 100644 index 0000000..3aead86 --- /dev/null +++ b/scripts/sql/add-product-item-supply-price.sql @@ -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 表示未维护'; diff --git a/scripts/sql/add-product-list-filter-indexes.sql b/scripts/sql/add-product-list-filter-indexes.sql new file mode 100644 index 0000000..a803903 --- /dev/null +++ b/scripts/sql/add-product-list-filter-indexes.sql @@ -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; diff --git a/scripts/sql/migrate-product-code-constraints.sql b/scripts/sql/migrate-product-code-constraints.sql new file mode 100644 index 0000000..34fe6c7 --- /dev/null +++ b/scripts/sql/migrate-product-code-constraints.sql @@ -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; diff --git a/scripts/sql/migrate-product-groups-and-category-properties.sql b/scripts/sql/migrate-product-groups-and-category-properties.sql new file mode 100644 index 0000000..8660199 --- /dev/null +++ b/scripts/sql/migrate-product-groups-and-category-properties.sql @@ -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; diff --git a/scripts/sql/migrate-product-status-and-sku-archive.sql b/scripts/sql/migrate-product-status-and-sku-archive.sql index e2ad4c6..6e4a586 100644 --- a/scripts/sql/migrate-product-status-and-sku-archive.sql +++ b/scripts/sql/migrate-product-status-and-sku-archive.sql @@ -1,6 +1,6 @@ -- One-time migration for product lifecycle statuses and SKU archival. -- Run during a maintenance window before deploying the product-service code --- that uses PRODUCT_STATUS_INVENTORY / ON_SALE / OFF_SALE. +-- that uses PRODUCT_STATUS_INVENTORY / ON_SALE / SOLD_OUT. BEGIN; @@ -20,7 +20,7 @@ ALTER TABLE product.product_items ALTER TABLE product.products DROP CONSTRAINT IF EXISTS chk_products_status; --- Current values are 0=DRAFT, 1=ON_SALE, 3=OFF_SALE. Value 2 has no +-- 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. UPDATE product.products SET status = CASE status @@ -38,17 +38,14 @@ ALTER TABLE product.products COMMIT; --- CREATE INDEX CONCURRENTLY cannot run inside the transaction above. -CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_product_items_sku_no_active - ON product.product_items (sku_no) - WHERE sku_no IS NOT NULL - AND deleted_at IS NULL - AND is_archived = FALSE; +-- SKU business codes are no longer unique. Remove the legacy uniqueness index +-- when this migration is applied to an existing deployment. +DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no_active; CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_items_active_product_id ON product.product_items (product_id) WHERE deleted_at IS NULL AND is_archived = FALSE; --- Drop the legacy index only after uq_product_items_sku_no_active is valid. +-- Remove the older legacy index as well, if it is still present. DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no; diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index c83d36f..18c434e 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -3,6 +3,8 @@ -- -- Tables: -- product.products +-- product.catalog_category +-- product.product_catalog_bindings -- product.product_category -- product.product_category_bindings -- product.product_items @@ -15,6 +17,7 @@ -- Drop order, if needed: -- DROP TABLE IF EXISTS product.product_item_inventory; -- DROP TABLE IF EXISTS product.product_category_bindings; +-- DROP TABLE IF EXISTS product.product_catalog_bindings; -- DROP TABLE IF EXISTS product.product_items; -- DROP TABLE IF EXISTS product.product_category; -- DROP TABLE IF EXISTS product.products; @@ -45,15 +48,23 @@ CREATE TABLE IF NOT EXISTS product.products ( 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, deleted_at TIMESTAMPTZ, 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)), 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) ); @@ -107,18 +128,24 @@ CREATE INDEX IF NOT EXISTS idx_products_active_created_id CREATE UNIQUE INDEX IF NOT EXISTS uq_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, node_type SMALLINT NOT NULL DEFAULT 1, 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, 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_product_category_node_type CHECK (node_type IN (1, 2)), CONSTRAINT chk_product_category_level @@ -129,37 +156,80 @@ CREATE TABLE IF NOT EXISTS product.product_category ( CHECK (version >= 0) ); -COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组'; -COMMENT ON COLUMN product.product_category.id IS '类别/分组节点主键'; -COMMENT ON COLUMN product.product_category.node_type IS '节点类型:1 分类,2 分组'; -COMMENT ON COLUMN product.product_category.name IS '节点展示名称'; -COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; -COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3'; -COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; -COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前'; -COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示'; -COMMENT ON COLUMN product.product_category.version IS '节点乐观锁版本号,更新时递增'; +COMMENT ON TABLE product.catalog_category IS '商品目录分类表:存储原商品分类和商品分组,通过 node_type 区分分类或分组'; +COMMENT ON COLUMN product.catalog_category.id IS '类别/分组节点主键'; +COMMENT ON COLUMN product.catalog_category.node_type IS '节点类型:1 分类,2 分组'; +COMMENT ON COLUMN product.catalog_category.name IS '节点展示名称'; +COMMENT ON COLUMN product.catalog_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; +COMMENT ON COLUMN product.catalog_category.level IS '节点层级,如 1、2、3'; +COMMENT ON COLUMN product.catalog_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; +COMMENT ON COLUMN product.catalog_category.sort_num IS '排序值,数值越小越靠前'; +COMMENT ON COLUMN product.catalog_category.status IS '节点状态:0 隐藏,1 显示'; +COMMENT ON COLUMN product.catalog_category.version IS '节点乐观锁版本号,更新时递增'; -CREATE INDEX IF NOT EXISTS idx_product_category_parent_id - ON product.product_category (parent_id); +CREATE INDEX IF NOT EXISTS idx_catalog_category_parent_id + ON product.catalog_category (parent_id); -CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort - ON product.product_category (node_type, status, sort_num); +CREATE INDEX IF NOT EXISTS idx_catalog_category_node_status_sort + 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, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, - category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE, - CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id) + 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_category_bindings IS '商品类别/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系'; -COMMENT ON COLUMN product.product_category_bindings.id IS '商品类别/分组绑定主键'; -COMMENT ON COLUMN product.product_category_bindings.product_id IS '绑定商品 SPU ID,对应 product.products.id'; -COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类/分组节点 ID,对应 product.product_category.id'; +COMMENT ON TABLE product.product_catalog_bindings IS '商品目录分类/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系'; +COMMENT ON COLUMN product.product_catalog_bindings.id IS '商品类别/分组绑定主键'; +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_category_bindings_category_id - ON product.product_category_bindings (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; + +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 ( id BIGINT PRIMARY KEY, @@ -167,6 +237,7 @@ CREATE TABLE IF NOT EXISTS product.product_items ( 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 '{}', 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 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 启用'; @@ -198,9 +270,7 @@ CREATE INDEX IF NOT EXISTS idx_product_items_price ON product.product_items (price) WHERE deleted_at IS NULL; -CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active - ON product.product_items (sku_no) - WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE; +-- SKU business codes are not unique; use the SKU primary key for identity. CREATE TABLE IF NOT EXISTS product.product_item_inventory ( 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 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; CREATE TRIGGER set_products_updated_at 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(); 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_bindings TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory TO svc_product; GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.suppliers TO svc_product; +GRANT SELECT, INSERT, UPDATE, DELETE ON product.brands TO svc_product;