From 5191d1981f929717d64ec0355fbf4a85380ccff0 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Sat, 11 Jul 2026 15:19:35 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BB=93=E5=82=A8=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E3=80=81=E8=8F=9C=E5=8D=95=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E6=89=A9=E5=B1=95=E5=8F=8A=E7=9B=B8=E5=85=B3=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增仓储模块页面与 API、店铺授权/店铺订单页面及路由权限目录; 扩展菜单管理同步能力支持二级子菜单与三级按钮;优化公告、仓库地址、下单等页面。 Co-authored-by: Cursor --- .env.development | 4 + docs/仓储模块设计方案.md | 1193 +++++++++++++++++ docs/订单全链路自动化测试方案.md | 602 +++++++++ docs/订单批量处理与异步队列方案0707.md | 664 +++++++++ scripts/scan-report.txt | 67 + src/api/order/platformStore.ts | 47 + src/api/warehouse/index.ts | 57 + src/components/HandsontablePro/index.vue | 46 +- src/components/top-nav/RightTopMessage.vue | 2 - src/constants/pageButtonCatalog.ts | 31 + src/locale/en-US.ts | 170 +++ src/locale/zh-CN.ts | 170 +++ src/router/routes/newModules/order.ts | 20 + src/router/routes/newModules/warehouse.ts | 58 + src/utils/syncMenuLevel3Buttons.ts | 170 ++- src/utils/syncMenuRouteCatalog.ts | 128 ++ .../components/FormulaConditionEditor.vue | 9 +- src/views/channel/autoTrigger/formulaMeta.ts | 19 +- src/views/channel/autoTrigger/index.vue | 252 ++-- .../components/FormLabelWithPreview.vue | 15 +- .../workplace/components/announcement.vue | 1 - .../workplace/components/notice-popup.vue | 1 - src/views/order/placeOrder/index.vue | 322 ++++- src/views/order/platformStore/index.vue | 214 +++ src/views/order/platformStoreOrder/index.vue | 311 +++++ src/views/system/announcement/index.vue | 811 ++++++++--- src/views/system/permission/menu/index.vue | 67 +- src/views/system/warehouseAddress/index.vue | 289 ++-- src/views/warehouse/inboundNotice/index.vue | 316 +++++ src/views/warehouse/inventory/index.vue | 233 ++++ src/views/warehouse/parcel/index.vue | 226 ++++ src/views/warehouse/sku/index.vue | 255 ++++ .../__pycache__/agent_worker.cpython-314.pyc | Bin 6341 -> 5329 bytes .../__pycache__/config_store.cpython-314.pyc | Bin 3490 -> 3554 bytes .../__pycache__/engine_path.cpython-314.pyc | Bin 0 -> 2129 bytes .../__pycache__/main_window.cpython-314.pyc | Bin 24494 -> 30832 bytes .../oms_agent_runner.cpython-314.pyc | Bin 0 -> 13632 bytes .../__pycache__/oms_client.cpython-314.pyc | Bin 0 -> 8887 bytes .../__pycache__/pair_server.cpython-314.pyc | Bin 0 -> 9593 bytes .../engine/.xhs_bridge/human_behavior.json | 109 ++ .../__pycache__/__init__.cpython-314.pyc | Bin 0 -> 357 bytes .../__pycache__/config.cpython-314.pyc | Bin 0 -> 16867 bytes .../__pycache__/exceptions.cpython-314.pyc | Bin 0 -> 1520 bytes .../human_behavior.cpython-314.pyc | Bin 0 -> 33905 bytes .../__pycache__/human_guard.cpython-314.pyc | Bin 0 -> 36663 bytes .../__pycache__/license.cpython-314.pyc | Bin 0 -> 14149 bytes .../__pycache__/license_codes.cpython-314.pyc | Bin 0 -> 7923 bytes .../__pycache__/service.cpython-314.pyc | Bin 0 -> 28077 bytes .../__pycache__/skills_client.cpython-314.pyc | Bin 0 -> 22872 bytes .../skills_process_manager.cpython-314.pyc | Bin 0 -> 10928 bytes .../skills_tool_adapter.cpython-314.pyc | Bin 0 -> 12805 bytes .../subprocess_win.cpython-314.pyc | Bin 0 -> 1493 bytes .../__pycache__/tools_catalog.cpython-314.pyc | Bin 0 -> 6310 bytes 53 files changed, 6329 insertions(+), 550 deletions(-) create mode 100644 docs/仓储模块设计方案.md create mode 100644 docs/订单全链路自动化测试方案.md create mode 100644 docs/订单批量处理与异步队列方案0707.md create mode 100644 scripts/scan-report.txt create mode 100644 src/api/order/platformStore.ts create mode 100644 src/api/warehouse/index.ts create mode 100644 src/router/routes/newModules/warehouse.ts create mode 100644 src/utils/syncMenuRouteCatalog.ts create mode 100644 src/views/order/platformStore/index.vue create mode 100644 src/views/order/platformStoreOrder/index.vue create mode 100644 src/views/warehouse/inboundNotice/index.vue create mode 100644 src/views/warehouse/inventory/index.vue create mode 100644 src/views/warehouse/parcel/index.vue create mode 100644 src/views/warehouse/sku/index.vue create mode 100644 xhs-agent-desktop/app/__pycache__/engine_path.cpython-314.pyc create mode 100644 xhs-agent-desktop/app/__pycache__/oms_agent_runner.cpython-314.pyc create mode 100644 xhs-agent-desktop/app/__pycache__/oms_client.cpython-314.pyc create mode 100644 xhs-agent-desktop/app/__pycache__/pair_server.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/.xhs_bridge/human_behavior.json create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/__init__.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/config.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/exceptions.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/human_behavior.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/human_guard.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/license.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/license_codes.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/service.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/skills_client.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/skills_process_manager.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/skills_tool_adapter.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/subprocess_win.cpython-314.pyc create mode 100644 xhs-agent-desktop/engine/xhs_bridge/__pycache__/tools_catalog.cpython-314.pyc diff --git a/.env.development b/.env.development index 7266978..1925bf9 100644 --- a/.env.development +++ b/.env.development @@ -1,5 +1,9 @@ # VITE_API_BASE_URL='http://localhost:5173/' +# 本地开发统一走线上 Admin API(与 /rbac、/order 等 Vite 代理一致) +VITE_OMS_ADMIN_URL=http://api.nanafa.com/admin +VITE_API_ADMIN_URL=http://api.nanafa.com/admin + # 智谱 AI(接口映射脚本生成) # 在 https://open.bigmodel.cn 申请 API Key VITE_ZHIPU_API_KEY=85bbbef6bafd4ca383eef04189decd07.lKVQHcLGtYE8oUn5 diff --git a/docs/仓储模块设计方案.md b/docs/仓储模块设计方案.md new file mode 100644 index 0000000..c904c9c --- /dev/null +++ b/docs/仓储模块设计方案.md @@ -0,0 +1,1193 @@ +# OMS 仓储模块 — 产品与技术设计方案 + +> **版本**:v0.3(轻量版 + `C_` 表前缀 + 库位 + 入库箱) +> **基线文档**:`docs/oms系统设计-050801.md`、`docs/rbac系统设计-060801.md`、`docs/前端页面设计规范.md` +> **参考实现**:WMS 六页业务逻辑(**按需裁剪,不做完整 WMS**) +> **对照仓库**:`C:\Users\wilso\Desktop\oms0414-back`(Fake 框架 + SqlSugar) + +--- + +## 0 轻量版总览(推荐阅读) + +> v0.1 按 WMS 能力完整对标,**表多、接口多、状态细**。若目标仅是「客户能管 SKU、预报入库、看库存、接店铺单发货」,采用本节 **轻量版** 即可,全文 §1~§11 中标注 **〔轻量〕** / **〔延后〕** 处以此为准。 + +### 0.1 设计取向 + +| 项 | v0.1 完整版 | **v0.3 轻量版(当前)** | +| --- | --- | --- | +| 定位 | 对标 WMS 仓储子系统 | OMS 附属 **基础仓储**,保留库位与入库箱 | +| **仓储表命名** | `t_wh_*` | **`C_` + 表名**(如 `C_sku`、`C_inventory`) | +| 数据表 | 18 张 | **13 张**(店铺 4 `t_*` + 仓储 9 `C_*`) | +| 后端 Service | 6 个 | **3 个**(店铺 2 + 仓储 1) | +| 库存模型 | 批次 lot + 冻结 + 流水 | **SKU × 仓库 × 库位** 余额,不做 FIFO/流水 | +| 入库预报 | 箱 → SKU + 收货日志 | **主表 + 箱 + 箱内 SKU**(保留箱号) | +| 组合 SKU / 库存同步 / 拆单 | 一期设计 | **延后** | +| 权限粒度 | 20+ Action | **每页 Query + Save + Delete**(库存加 Relocate) | + +### 0.2 表清单 + +**命名约定** + +| 范围 | 前缀 | 示例 | +| --- | --- | --- | +| 仓储模块(本文) | **`C_`** | `C_sku`、`C_inventory`、`C_inbound_box` | +| 订单 — 店铺(归属订单模块) | `t_` | `t_sales_store`、`t_sales_store_order` | +| 系统主数据 | `t_` | `t_warehouse_address` | + +**订单 — 店铺(4 张,`t_` 前缀)** + +| 表 | 说明 | +| --- | --- | +| `t_sales_store` | 店铺 + Token 合并(Token 加密,列表脱敏) | +| `t_sales_store_order` | 店铺订单主表 | +| `t_sales_store_order_line` | 订单明细 | +| `C_sku_platform_map` | 平台 SKU → 库内 SKU(发货匹配;归属仓储域,用 `C_`) | + +**仓储(9 张,`C_` 前缀)** + +| 表 | 说明 | +| --- | --- | +| `C_sku` | 我的 SKU | +| `C_bin_location` | 库位主数据(按仓库) | +| `C_inventory` | 库存余额:`CustomerId + WarehouseId + SkuId + BinLocationId → Qty` | +| `C_inbound_notice` | 入库预报主表 | +| `C_inbound_box` | 入库箱(箱号/箱唛) | +| `C_inbound_box_line` | 箱内 SKU 行 | +| `C_parcel` | 我的包裹 | +| `C_parcel_item` | 包裹明细 | + +**延后(相对 v0.1 / 原完整版)** + +| 原概念 | 处理 | +| --- | --- | +| `t_sales_store_token` | 合并进 `t_sales_store` | +| `t_sales_store_share` / 拆单 / 录单表 | 延后 | +| `C_sku_bundle`(组合 SKU) | 延后 | +| `C_stock_movement`(库存流水) | 延后 | +| `C_inbound_receipt_log`(收货日志) | 延后,状态字段够用 | + +### 0.3 轻量版核心流程(够用即可) + +```mermaid +flowchart LR + SKU["我的 SKU
C_sku"] --> MAP["平台映射
C_sku_platform_map"] + MAP --> PSO["店铺订单"] + BIN["库位
C_bin_location"] + IBN["入库预报
C_inbound_notice"] --> BOX["入库箱
C_inbound_box"] + BOX --> INV["库存
C_inventory"] + BIN --> INV + PAR["我的包裹
C_parcel"] -->|"上架到库位"| INV + PSO -->|"匹配库存"| INV + PSO -->|"生成小包单"| ORD["t_order"] +``` + +1. **我的 SKU**:维护库内编码 + 尺重;绑平台 SKU(`C_sku_platform_map`)。 +2. **库位**:按仓库维护 `C_bin_location`;库存按 **库位** 记数量。 +3. **入库预报**:主表 + **箱号**(`C_inbound_box`)+ 箱内 SKU(`C_inbound_box_line`);收货上架时写入 `C_inventory`。 +4. **我的库存**:按 SKU 汇总展示,可展开 **各库位明细**;支持 **换库位**(不调 FIFO、不记流水)。 +5. **我的包裹**:预报快递单号;到仓后上架到指定库位。 +6. **店铺订单**:库存匹配时按库位扣减 `C_inventory.Qty` 并建 `t_order`。 + +### 0.4 轻量版接口原则 + +- 每个页面 **列表 + 详情 + 保存 + 删除**;统计合并为 `summary`。 +- 仓储一个 `WarehouseService`(`/warehouse/*`)。 +- **保留**:库位列表、入库箱结构、换库位、上架指定库位。 +- **不做**:库存流水、FIFO 批次、冻结量、组合 SKU、平台库存回写。 + +### 0.5 轻量版实施顺序 + +| 阶段 | 交付 | 说明 | 状态 | +| --- | --- | --- | --- | +| **Step 1 表** | SQL + SqlSugar 实体 | `sql/migrate_warehouse_module.sql` + `Oms.Domain` 实体 | **已完成** | +| **Step 2 接口** | `WarehouseService` + 店铺 Service | `/warehouse/*`、`/order/platform-store*` | **已完成** | +| **Step 3 页面** | 前端 6 页 + 路由 + RBAC 菜单 | `views/warehouse/*`、`order/platformStore*` | **已完成** | + +**Step 2 交付物(2026-07-11)** + +| 层级 | 路径 | +| --- | --- | +| Repository | `Oms.Domain/WarehouseAggregate/Repositories`、`Oms.SqlSugarCore/Warehouse/`;`OrdersAggregate/Repositories`(店铺) | +| DTO | `Oms.Application/Dtos/Warehouse/`、`Dtos/PlatformStore/` | +| Service | `Services/Warehouse/WarehouseService`;`PlatformStoreService`;`PlatformStoreOrderService` | + +**M1~M4 业务分期** + +| 阶段 | 交付 | 说明 | +| --- | --- | --- | +| **M1** | `C_sku` + `C_bin_location` + `C_inventory` + 入库预报(含箱) | 5 张 `C_*` 表 + 约 12 接口 | +| **M2** | `C_parcel` + 库存列表/换库位 | +2 张表 + 2 页 | +| **M3** | 店铺授权 + 店铺订单 | +3 表 + 2 Service + 2 页 | +| **M4** | 库存匹配 → `t_order` | 打通订单 | **已完成** | + +**M4 交付物(2026-07-11)** + +| 项 | 说明 | +| --- | --- | +| `PlatformStoreOrderParcelBuilder` | 店铺订单 → `OrderParcelCreateInput` | +| `POST /order/platform-store-order/match-inventory` | 扣库存 → 创建小包 → 回写 `LinkedOrderId` | +| `POST /order/platform-store-order/batch-match-inventory` | 批量匹配 | +| 前端 | 销售产品选择、关联服务单号、批量匹配按钮 | + +--- + +## 1 导读 + +### 1.1 这份文档解决什么问题? + +将 WMS 中与客户履约相关的 **6 个页面** 迁入 OMS,拆为两块: + +| 归属 | 页面 | 原 WMS 路由(参考) | +| --- | --- | --- | +| **订单模块**(扩展现有 §4) | 店铺授权、店铺订单 | `/order/platform/shop`、`/order/platform/shop-orderv2` | +| **仓储模块**(本文新建 §9) | 我的包裹、我的库存、我的 SKU、入库预报 | `/wms/package/package`、`/wms/stock/myinventory2`、`/wms/stock/merchants`、`/wms/stock/warehousingorder` | + +设计原则: + +1. **表名、字段名、接口路径全部重新命名**,不沿用 WMS 的 `vip_*` / `wms_*` 命名。 +2. **业务逻辑对齐 WMS**,在 OMS 会话隔离、分页规范、审计字段上对齐现有 OMS 约定。 +3. **与现有 OMS 模块边界清晰**:小包订单(`t_order`)与仓储库存(`C_*`)分离;店铺订单通过 `C_sku_platform_map` 匹配库存。 + +### 1.2 与 OMS 其它模块的关系 + +```mermaid +flowchart TB + subgraph Order["订单模块 §4"] + PS["店铺授权
t_sales_store"] + PSO["店铺订单
t_sales_store_order"] + PO["小包订单
t_order"] + end + subgraph Warehouse["仓储模块 C_*"] + BIN["库位
C_bin_location"] + PAR["我的包裹
C_parcel"] + SKU["我的 SKU
C_sku"] + INV["库存
C_inventory"] + IBN["入库预报
C_inbound_notice"] + end + subgraph System["系统主数据 §8"] + WA["仓库地址
t_warehouse_address"] + end + subgraph Operation["操作模块 §6"] + INB["入库扫描
t_inbound_record"] + OUT["出库扫描
t_outbound_record"] + end + + PS --> PSO + PSO -->|"SKU 映射 + 库存匹配"| SKU + PSO -->|"一键发货 / 录单"| PO + PAR --> INV + IBN --> INV + BIN --> INV + SKU --> INV + WA --> PAR + WA --> IBN + INB -.->|"小包运单收货"| PO + OUT -.->|"小包运单出库"| PO +``` + +| 边界 | 说明 | +| --- | --- | +| `t_order` vs `t_sales_store_order` | 前者为 OMS 小包物流订单;后者为电商平台拉取的 **店铺履约单**,二者通过 `LinkedOrderId` 可选关联 | +| `t_warehouse_address` | 仓储业务统一引用系统主数据仓库(`WarehouseId` → `t_warehouse_address.Id`),**不新建**客户侧仓库表 | +| `t_inbound_record` / `t_outbound_record` | 面向 **小包运单**(`WaybillNo`)的仓内扫描;与仓储模块的 **SKU 入库预报 / 包裹到仓** 是不同业务线,表不合并 | +| 客户隔离 | 全模块 `CustomerId` → `t_customer.Id`;规则同 OMS §3.3.5 / §4.4.0 | + +### 1.3 建议阅读路径 + +| 角色 | 路径 | +| --- | --- | +| 产品 / 测试 | **§2 页面与菜单** → **§5 主流程** → **§8 枚举** | +| 后端 / DBA | **§3 表结构** → **§4 接口** → **§7 WMS 对照** | +| 前端 | **§2** → **§4** → `docs/前端页面设计规范.md` | + +--- + +## 2 页面、路由与权限 + +### 2.1 菜单结构 + +``` +订单(已有 /order) +├── …(查价、下单、我的订单等) +├── 店铺授权 /order/platformStore +└── 店铺订单 /order/platformStoreOrder + +仓储(新建 /warehouse) +├── 我的包裹 /warehouse/parcel +├── 我的库存 /warehouse/inventory +├── 我的 SKU /warehouse/sku +└── 入库预报 /warehouse/inboundNotice +``` + +### 2.2 前端路由(`src/router/routes/newModules/`) + +**订单模块扩展**(`order.ts` 追加 children): + +| path | name | component | permission | +| --- | --- | --- | --- | +| `platformStore` | `OrderPlatformStore` | `views/order/platformStore/index.vue` | `Order.PlatformStore.Query` | +| `platformStoreOrder` | `OrderPlatformStoreOrder` | `views/order/platformStoreOrder/index.vue` | `Order.PlatformStoreOrder.Query` | + +**仓储模块新建**(`warehouse.ts`): + +| path | name | component | permission | +| --- | --- | --- | --- | +| `parcel` | `WarehouseParcel` | `views/warehouse/parcel/index.vue` | `Warehouse.Parcel.Query` | +| `inventory` | `WarehouseInventory` | `views/warehouse/inventory/index.vue` | `Warehouse.Inventory.Query` | +| `sku` | `WarehouseSku` | `views/warehouse/sku/index.vue` | `Warehouse.Sku.Query` | +| `inboundNotice` | `WarehouseInboundNotice` | `views/warehouse/inboundNotice/index.vue` | `Warehouse.InboundNotice.Query` | + +列表页布局遵循 `docs/前端页面设计规范.md`:`xxx-container`、`table-toolbar`、分页右上角、`PaginationPro` 默认 30 条。 + +### 2.3 RBAC 权限码 + +格式:`{Module}.{Resource}.{Action}`(与 RBAC §5.2 一致)。 + +#### 2.3.1 订单 — 店铺域 + +| 权限码 | 说明 | +| --- | --- | +| `Order.PlatformStore` | 店铺授权模块 | +| `Order.PlatformStore.Query` | 列表 / 详情 | +| `Order.PlatformStore.Create` | 新增授权 / OAuth 回调落库 | +| `Order.PlatformStore.Update` | 改名、自动发货开关 | +| `Order.PlatformStore.Delete` | 删除店铺 | +| `Order.PlatformStoreOrder` | 店铺订单模块 | +| `Order.PlatformStoreOrder.Query` | 列表 / 详情 / 状态统计 | +| `Order.PlatformStoreOrder.Sync` | 同步平台状态 | +| `Order.PlatformStoreOrder.Rts` | 准备发货(Ready To Ship) | +| `Order.PlatformStoreOrder.AutoMatch` | 库存匹配生成小包订单 | +| `Order.PlatformStoreOrder.Suspend` | 搁置 / 取消搁置 | +| `Order.PlatformStoreOrder.Delete` | 删除 | +| `Order.PlatformStoreOrder.Export` | 导出 | +| `Order.PlatformStoreOrder.Label` | 获取 / 打印面单 | +| `Order.PlatformStoreOrder.Tag` | 自定义标签 | + +#### 2.3.2 仓储域 **〔轻量:每资源 3 个权限即可〕** + +| 权限码 | 说明 | +| --- | --- | +| `Warehouse.Sku.Query` / `.Save` / `.Delete` | 我的 SKU | +| `Warehouse.InboundNotice.Query` / `.Save` / `.Delete` | 入库预报 | +| `Warehouse.Parcel.Query` / `.Save` / `.Delete` | 我的包裹 | +| `Warehouse.Inventory.Query` / `.Relocate` | 我的库存(查询 + 换库位) | +| `Warehouse.BinLocation.Query` / `.Save` | 库位维护(管理端/仓库端) | + +**〔延后〕**:ApplyStorage、Putaway、Relocate、Adjust、Import、Mapping、Print 等细粒度 Action — 首期 Save 接口内覆盖。 + +### 2.4 后端 Service 与路由前缀 **〔轻量〕** + +| 业务域 | Service 类 | 路由前缀 | +| --- | --- | --- | +| 店铺授权 | `PlatformStoreService` | `/order/platform-store/*` | +| 店铺订单 | `PlatformStoreOrderService` | `/order/platform-store-order/*` | +| 仓储(合并) | **`WarehouseService`** | `/warehouse/*` | + +> 轻量版仓储 **一个 Service** 即可,按子路径分 SKU / 入库 / 包裹 / 库存。 + +--- + +## 3 数据表结构设计 + +> 遵循 OMS §3.1 公共规范。 +> **轻量版以 §0.2 为准**;下列分节含完整版字段,标注 **〔延后〕** 的表/字段在轻量版中不建。 + +### 3.0 轻量版表结构(v0.3 推荐落地) + +> **仓储表一律 `C_` 前缀**;字段仍用 OMS 驼峰(`PascalCase`);必备审计字段见 §3.1 公共规范。 + +#### 3.0.1 `t_sales_store`(店铺,含 Token) + +在 §3.1.1 基础上 **合并** Token,新增:`AccessToken`、`RefreshToken`、`TokenExtraJson`(加密,列表脱敏)。 + +#### 3.0.2 `C_sku`(我的 SKU) + +| 字段 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 | +| SkuCode | VARCHAR(64) | 是 | 库内编码 | +| SkuName | VARCHAR(256) | 是 | 名称 | +| SkuImageUrl | VARCHAR(512) | 否 | 图片 | +| WeightG / LengthCm / WidthCm / HeightCm | DECIMAL | 否 | 尺重 | +| Remark | VARCHAR(512) | 否 | 备注 | +| 审计字段 | — | 是 | | + +**索引**:`uk_c_sku_code` (`CustomerId`, `SkuCode`)。 + +#### 3.0.3 `C_bin_location`(库位) + +| 字段 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| WarehouseId | BIGINT | 是 | → `t_warehouse_address.Id` | +| BinCode | VARCHAR(32) | 是 | 库位编码,如 `A-01-02` | +| BinName | VARCHAR(64) | 否 | 展示名称 | +| ZoneCode | VARCHAR(32) | 否 | 库区 | +| IsEnabled | TINYINT | 是 | 是否启用,默认 1 | +| Remark | VARCHAR(512) | 否 | 备注 | +| 审计字段 | — | 是 | | + +**索引**:`uk_c_bin_wh_code` (`WarehouseId`, `BinCode`)。 + +> 库位为 **仓库级主数据**(不按客户拆分);库存余额按客户 + 库位区分。 + +#### 3.0.4 `C_inventory`(库存余额) + +| 字段 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 | +| WarehouseId | BIGINT | 是 | 仓库 | +| SkuId | BIGINT | 是 | → `C_sku.Id` | +| BinLocationId | BIGINT | 是 | → `C_bin_location.Id` | +| Qty | INT | 是 | 可用数量(匹配时直接扣减) | +| 审计字段 | — | 是 | | + +**唯一索引**:`uk_c_inventory` (`CustomerId`, `WarehouseId`, `SkuId`, `BinLocationId`)。 + +> 「我的库存」列表:按 `SkuId` 聚合 `SUM(Qty)`;详情/换库位:按 `BinLocationId` 展开。 +> **不做**冻结量、FIFO 批次、库存流水表。 + +#### 3.0.5 `C_inbound_notice` + `C_inbound_box` + `C_inbound_box_line`(入库预报,含箱号) + +**主表 `C_inbound_notice`** + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| CustomerId | BIGINT | 客户 | +| WarehouseId | BIGINT | 仓库 | +| NoticeNo | VARCHAR(32) | `IN` + 雪花 | +| MarkReference | VARCHAR(64) | 唛头 | +| InboundType | VARCHAR(16) | `normal` / `return` | +| ReceiptStatus | VARCHAR(16) | `forecasted` → `received` → `completed` | +| ExpectedArrivalTime | DATETIME | 可选 | +| ActualArrivalTime | DATETIME | 收货时写入 | +| Remark | VARCHAR(512) | | + +**箱表 `C_inbound_box`** + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| InboundNoticeId | BIGINT | 主表 | +| BoxSeqNo | VARCHAR(16) | 箱序号 | +| MarkBoxNo | VARCHAR(64) | **箱唛号/箱号** | +| WeightG | DECIMAL(10,2) | 箱重(g),可选 | +| LengthCm / WidthCm / HeightCm | DECIMAL | 箱尺寸,可选 | +| IsReceived | TINYINT | 是否已收货 | + +**箱内 SKU 行 `C_inbound_box_line`** + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| InboundBoxId | BIGINT | 箱 | +| SkuId | BIGINT | → `C_sku.Id` | +| SkuCode | VARCHAR(64) | 冗余编码 | +| PlannedQty | INT | 计划数量 | +| ReceivedQty | INT | 实收数量 | +| BinLocationId | BIGINT | 上架库位(收货确认时填入) | + +**收货上架逻辑**:`confirm-receive` 按箱清点 → 按行 `ReceivedQty` + `BinLocationId` **累加** `C_inventory.Qty` → 主表 `completed`。 + +#### 3.0.6 `C_parcel` + `C_parcel_item`(我的包裹) + +**主表**:`TrackingNo`、`CarrierName`、`WarehouseId`、`LifecycleStatus`(`inTransit` / `arrived` / `stored`)、`ArrivalTime`、`Remark`。 + +**明细**:`ProductName`、`Quantity`、`SkuId`(上架时关联)、`BinLocationId`(上架库位,可选)。 + +#### 3.0.7 `C_sku_platform_map`(平台 SKU 映射) + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| CustomerId | BIGINT | 客户 | +| StoreId | BIGINT | → `t_sales_store.Id` | +| PlatformSku | VARCHAR(128) | 平台 listing SKU | +| SkuId | BIGINT | → `C_sku.Id` | +| SkuCode | VARCHAR(64) | 冗余 | + +**索引**:`uk_c_sku_map` (`StoreId`, `PlatformSku`)。 + +#### 3.0.8 `t_sales_store_order`(店铺订单,字段精简) + +保留核心字段 + 明细行;`MappedSkuId` 指向 `C_sku.Id`。拆单/录单表延后。 + +--- + +### 3.1 订单模块 — 店铺授权 + +#### 3.1.1 销售店铺表 `t_sales_store` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 Id | +| PlatformCode | VARCHAR(32) | 是 | 平台:`lazada` / `shopee` / `tiktok` / `temu` / `manual` | +| StoreNickname | VARCHAR(128) | 是 | 店铺昵称(用户自定义) | +| PlatformStoreId | VARCHAR(64) | 否 | 平台侧店铺 Id | +| PlatformAccount | VARCHAR(128) | 否 | 平台账号 | +| SiteCountry | VARCHAR(8) | 否 | 开户站点国家码 | +| SellerId | VARCHAR(64) | 否 | 平台卖家 Id | +| AuthStatus | VARCHAR(16) | 是 | `active` / `expired` / `revoked` | +| AuthTime | DATETIME | 否 | 授权时间 | +| TokenExpireTime | DATETIME | 否 | Access Token 过期 | +| RefreshExpireTime | DATETIME | 否 | Refresh Token 过期 | +| IsAutoFulfill | TINYINT | 是 | 是否自动发货,默认 0 | +| SortOrder | INT | 否 | 排序 | +| Remark | VARCHAR(512) | 否 | 备注 | +| IsDeleted / 审计字段 | — | 是 | 见 §3.1 公共规范 | + +**索引**:`idx_sales_store_customer` (`CustomerId`, `IsDeleted`);`uk_sales_store_platform` (`CustomerId`, `PlatformCode`, `PlatformStoreId`) 唯一(`PlatformStoreId` 为空时 manual 店铺允许多条)。 + +#### 3.1.2 店铺授权凭证表 `t_sales_store_token` **〔轻量:合并至 3.0.1,不单独建表〕** + +> 敏感字段加密存储;列表接口 **不返回** `AccessToken` / `RefreshToken` 明文。 + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| StoreId | BIGINT | 是 | → `t_sales_store.Id` | +| AccessToken | VARCHAR(2048) | 否 | 加密 | +| RefreshToken | VARCHAR(2048) | 否 | 加密 | +| TokenType | VARCHAR(32) | 否 | 默认 `Bearer` | +| Scope | VARCHAR(512) | 否 | 授权范围 | +| ExtraJson | JSON | 否 | 平台扩展(如 Lazada 多站点 userId) | +| IsDeleted / 审计字段 | — | 是 | | + +#### 3.1.3 店铺共享表 `t_sales_store_share` **〔延后〕** + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| StoreId | BIGINT | 是 | 主店铺 | +| SharedCustomerId | BIGINT | 是 | 被共享的子客户 Id | +| IsDeleted / 审计字段 | — | 是 | | + +--- + +### 3.2 订单模块 — 店铺订单 + +#### 3.2.1 店铺订单表 `t_sales_store_order` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 Id | +| StoreId | BIGINT | 是 | → `t_sales_store.Id` | +| PlatformCode | VARCHAR(32) | 是 | 冗余平台码 | +| PlatformOrderNo | VARCHAR(64) | 是 | 平台订单号 | +| OrderCountry | VARCHAR(8) | 否 | 订单国家 | +| ItemCount | INT | 否 | 商品行数 | +| TotalAmount | DECIMAL(18,4) | 否 | 订单总额 | +| Currency | VARCHAR(8) | 否 | 币种 | +| PaymentMethod | VARCHAR(64) | 否 | 付款方式 | +| PlatformOrderTime | DATETIME | 否 | 平台下单时间 | +| PlatformPayTime | DATETIME | 否 | 平台付款时间 | +| FulfillStatus | VARCHAR(32) | 是 | 履约状态,见 §8.1 | +| PlatformStatus | VARCHAR(64) | 否 | 平台原始状态码 | +| PlatformStatusLabel | VARCHAR(128) | 否 | 平台状态展示文案 | +| ShippingLabelNo | VARCHAR(64) | 否 | 面单号 | +| ShippingLabelUrl | VARCHAR(512) | 否 | 面单文件 URL | +| IsMultiLabel | TINYINT | 是 | 是否多面单/拆单 | +| DeliveryMethod | VARCHAR(64) | 否 | 运输方式 code | +| DeliveryMethodLabel | VARCHAR(128) | 否 | 运输方式展示 | +| DeliveryStatus | VARCHAR(32) | 否 | 物流子状态 | +| ShippingCarrier | VARCHAR(64) | 否 | 物流承运商 | +| PickupType | VARCHAR(32) | 否 | 取件类型:`pickup` / `dropoff` | +| CustomTags | VARCHAR(512) | 否 | 用户自定义标签,逗号分隔 | +| IsSuspended | TINYINT | 是 | 是否搁置 | +| PresaleDays | INT | 否 | 预售天数 | +| BuyerRemark | VARCHAR(1024) | 否 | 买家备注 | +| SellerPickRemark | VARCHAR(1024) | 否 | 卖家拣货备注 | +| SellerPickRemarkTime | DATETIME | 否 | 拣货备注时间 | +| WarehouseId | BIGINT | 否 | 发货仓库 → `t_warehouse_address.Id` | +| LinkedOrderId | BIGINT | 否 | 关联 OMS 小包订单 `t_order.Id` | +| LastSyncTime | DATETIME | 否 | 最近同步时间 | +| StatusChangedTime | DATETIME | 否 | 状态变更时间 | +| SystemShipTime | DATETIME | 否 | 系统发货时间 | +| SystemLabelPrintTime | DATETIME | 否 | 系统打印面单时间 | +| SystemPushTime | DATETIME | 否 | 推送到出库时间 | +| IsDeleted / 审计字段 | — | 是 | | + +**索引**:`uk_store_order_no` (`StoreId`, `PlatformOrderNo`);`idx_store_order_customer_status` (`CustomerId`, `FulfillStatus`, `PlatformOrderTime`)。 + +#### 3.2.2 店铺订单明细表 `t_sales_store_order_line` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| StoreOrderId | BIGINT | 是 | → `t_sales_store_order.Id` | +| PlatformLineId | VARCHAR(64) | 否 | 平台行 Id / itemId | +| PlatformSku | VARCHAR(128) | 否 | 平台 SKU | +| ProductName | VARCHAR(512) | 否 | 商品名称 | +| ProductImageUrl | VARCHAR(512) | 否 | 商品图 | +| ProductUrl | VARCHAR(512) | 否 | 商品链接 | +| VariantText | VARCHAR(256) | 否 | 规格属性 | +| UnitPrice | DECIMAL(18,4) | 否 | 单价 | +| Quantity | INT | 是 | 数量 | +| Currency | VARCHAR(8) | 否 | 币种 | +| IsShipExcluded | TINYINT | 是 | 是否拒绝发货 | +| MappedSkuId | BIGINT | 否 | 映射的仓储 SKU → `C_sku.Id` | +| IsDeleted / 审计字段 | — | 是 | | + +#### 3.2.3 店铺订单快速录单表 `t_sales_store_order_draft` **〔延后〕** + +#### 3.2.4 店铺订单拆单表 `t_sales_store_order_split` **〔延后〕** + +--- + +### 3.3 仓储模块 — 我的包裹 + +#### 3.3.1 客户包裹表 `C_parcel` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 Id | +| WarehouseId | BIGINT | 是 | → `t_warehouse_address.Id` | +| TrackingNo | VARCHAR(64) | 是 | 快递单号 | +| CarrierName | VARCHAR(64) | 否 | 快递公司 | +| SourcePlatform | VARCHAR(32) | 否 | 来源平台(淘宝、拼多多等) | +| ParcelCategory | VARCHAR(16) | 是 | `single` 一票一单 / `multi` 一票多单 / `unclaimed` 待认领 / `stock` 库存件 | +| LifecycleStatus | VARCHAR(16) | 是 | 见 §8.2:`inTransit` / `arrived` / `unclaimed` / `expired` | +| PurchaseOrderNo | VARCHAR(64) | 否 | 采购订单号(与 OMS 小包无关) | +| BizScene | VARCHAR(16) | 否 | 业务场景,如 `consolidation` 集运 | +| ImageUrl | VARCHAR(512) | 否 | 包裹图片 | +| LengthCm | DECIMAL(10,2) | 否 | 长(cm) | +| WidthCm | DECIMAL(10,2) | 否 | 宽(cm) | +| HeightCm | DECIMAL(10,2) | 否 | 高(cm) | +| VolumeCbm | DECIMAL(12,4) | 否 | 体积 | +| WeightKg | DECIMAL(10,3) | 否 | 重量(kg) | +| ArrivalTime | DATETIME | 否 | 到仓时间 | +| LinkedSkuId | BIGINT | 否 | 关联仓储 SKU | +| Remark | VARCHAR(512) | 否 | 备注 | +| IsDeleted / 审计字段 | — | 是 | | + +**索引**:`uk_c_parcel_tracking` (`CustomerId`, `TrackingNo`, `WarehouseId`);`idx_c_parcel_status` (`CustomerId`, `LifecycleStatus`)。 + +#### 3.3.2 包裹明细表 `C_parcel_item` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| ParcelId | BIGINT | 是 | → `C_parcel.Id` | +| ProductName | VARCHAR(512) | 否 | 商品名称 | +| ProductCategory | VARCHAR(64) | 否 | 商品分类 | +| Quantity | INT | 是 | 数量 | +| ImageUrl | VARCHAR(512) | 否 | 图片 | +| AttributeText | VARCHAR(256) | 否 | 属性 | +| SkuId | BIGINT | 否 | 库内 SKU(上架时关联) | +| SkuCode | VARCHAR(64) | 否 | 冗余编码 | +| BinLocationId | BIGINT | 否 | 上架库位 | +| IsDeleted / 审计字段 | — | 是 | | + +--- + +### 3.4 仓储模块 — 我的 SKU + +#### 3.4.1 仓储 SKU 主表 `C_sku` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 Id | +| SkuCode | VARCHAR(64) | 是 | 库内 SKU 编码 | +| SkuName | VARCHAR(256) | 是 | SKU 名称 | +| SkuImageUrl | VARCHAR(512) | 否 | 图片 | +| CategoryCode | VARCHAR(64) | 否 | 分类 | +| IsBundle | TINYINT | 是 | 是否组合 SKU | +| WeightG | DECIMAL(10,2) | 否 | 重量(g) | +| LengthCm | DECIMAL(10,2) | 否 | 长(cm) | +| WidthCm | DECIMAL(10,2) | 否 | 宽(cm) | +| HeightCm | DECIMAL(10,2) | 否 | 高(cm) | +| ReferencePrice | DECIMAL(18,4) | 否 | 参考价 | +| Currency | VARCHAR(8) | 否 | 币种 | +| Remark | VARCHAR(512) | 否 | 备注 | +| IsDeleted / 审计字段 | — | 是 | | + +**索引**:`uk_c_sku_code` (`CustomerId`, `SkuCode`)。 + +#### 3.4.2 组合 SKU 子项表 `C_sku_bundle_item` **〔延后〕** + +#### 3.4.3 平台 SKU 映射表 `C_sku_platform_map` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 Id | +| StoreId | BIGINT | 是 | → `t_sales_store.Id` | +| PlatformSku | VARCHAR(128) | 是 | 平台 listing SKU | +| PlatformProductId | VARCHAR(64) | 否 | 平台商品 Id | +| SkuId | BIGINT | 是 | → `C_sku.Id` | +| SkuCode | VARCHAR(64) | 是 | 冗余库内编码 | +| IsDeleted / 审计字段 | — | 是 | | + +**索引**:`uk_c_sku_map` (`StoreId`, `PlatformSku`)。 + +--- + +### 3.5 仓储模块 — 我的库存 + +#### 3.5.1 库存余额表 `C_inventory`(见 §3.0.4) + +#### 3.5.2 库位表 `C_bin_location`(见 §3.0.3) + +#### 3.5.3 库存流水表 `C_stock_movement` **〔延后〕** + +--- + +### 3.6 仓储模块 — 入库预报 + +#### 3.6.1 入库预报主表 `C_inbound_notice` + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| CustomerId | BIGINT | 是 | 客户 Id | +| WarehouseId | BIGINT | 是 | 仓库 | +| NoticeNo | VARCHAR(32) | 是 | 入库单号,规则 `IN` + 雪花 Id | +| MarkReference | VARCHAR(64) | 否 | 唛头参考号 | +| InboundType | VARCHAR(16) | 是 | `normal` 普通 / `return` 退货 | +| ReceiptStatus | VARCHAR(16) | 是 | 见 §8.4 | +| FirstMileCarrier | VARCHAR(64) | 否 | 头程物流 | +| FirstMileTrackingNo | VARCHAR(64) | 否 | 头程单号 | +| ExpectedArrivalTime | DATETIME | 否 | 预计到货 | +| ActualArrivalTime | DATETIME | 否 | 实际到货 | +| IsException | TINYINT | 是 | 是否异常件 | +| ExceptionNote | VARCHAR(1024) | 否 | 异常说明 | +| ExceptionImageUrls | VARCHAR(2048) | 否 | 异常图片,分号分隔 | +| CustomerFeedback | TINYINT | 否 | 客户是否已确认异常 | +| Remark | VARCHAR(512) | 否 | 备注 | +| IsDeleted / 审计字段 | — | 是 | | + +**索引**:`uk_c_inbound_notice_no` (`NoticeNo`);`idx_c_inbound_customer_status` (`CustomerId`, `ReceiptStatus`)。 + +#### 3.6.2 入库箱表 `C_inbound_box`(见 §3.0.5) + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| InboundNoticeId | BIGINT | 是 | → `C_inbound_notice.Id` | +| BoxSeqNo | VARCHAR(16) | 是 | 箱序号 | +| MarkBoxNo | VARCHAR(64) | 否 | 箱唛号/箱号 | +| WeightG | DECIMAL(10,2) | 否 | 箱重(g) | +| LengthCm / WidthCm / HeightCm | DECIMAL(10,2) | 否 | 箱尺寸 | +| IsReceived | TINYINT | 是 | 是否已收货 | +| 审计字段 | — | 是 | | + +#### 3.6.3 入库箱 SKU 行表 `C_inbound_box_line`(见 §3.0.5) + +| 字段名 | 类型 | 非空 | 说明 | +| --- | --- | --- | --- | +| Id | BIGINT | 是 | 主键 | +| InboundBoxId | BIGINT | 是 | → `C_inbound_box.Id` | +| SkuId | BIGINT | 是 | → `C_sku.Id` | +| SkuCode | VARCHAR(64) | 是 | 冗余编码 | +| PlannedQty | INT | 是 | 计划入库数量 | +| ReceivedQty | INT | 否 | 实收数量 | +| BinLocationId | BIGINT | 否 | 上架库位(收货时填) | +| 审计字段 | — | 是 | | + +#### 3.6.4 入库收货日志表 `C_inbound_receipt_log` **〔延后〕** + +--- + +## 4 接口设计 + +> 分页:`{ items, total }`;默认 `pageSize=30`。客户隔离同 §6。 +> **轻量版接口以 §4.0 为准**;§4.1~§4.6 为完整版参考。 + +### 4.0 轻量版接口清单(推荐) + +#### 仓储 `WarehouseService` — 共 **20 个** + +| 页面 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| SKU | POST | `/warehouse/sku/list` | 列表 | +| SKU | GET | `/warehouse/sku/detail` | 详情 | +| SKU | POST | `/warehouse/sku/save` | 新增/编辑 | +| SKU | POST | `/warehouse/sku/delete` | 删除 | +| SKU | POST | `/warehouse/sku/bind-mapping` | 绑定平台 SKU | +| 库位 | POST | `/warehouse/bin-location/list` | 按仓库查库位 | +| 库位 | POST | `/warehouse/bin-location/save` | 新增/编辑库位 | +| 入库 | POST | `/warehouse/inbound/list` | 列表 | +| 入库 | GET | `/warehouse/inbound/detail` | 详情含 `boxes[].lines[]` | +| 入库 | POST | `/warehouse/inbound/save` | 新增/编辑(含箱号,仅 forecasted) | +| 入库 | POST | `/warehouse/inbound/delete` | 删除 | +| 入库 | POST | `/warehouse/inbound/confirm-receive` | 按箱收货上架 → 写 `C_inventory` | +| 入库 | GET | `/warehouse/inbound/summary` | 状态 Tab 数量 | +| 包裹 | POST | `/warehouse/parcel/list` | 列表 | +| 包裹 | POST | `/warehouse/parcel/save` | 新增/编辑 | +| 包裹 | POST | `/warehouse/parcel/delete` | 删除 | +| 包裹 | POST | `/warehouse/parcel/putaway` | 到仓上架(指定 `binLocationId`) | +| 库存 | POST | `/warehouse/inventory/list` | 按 SKU 聚合列表 | +| 库存 | GET | `/warehouse/inventory/bin-detail` | 某 SKU 各库位明细 | +| 库存 | POST | `/warehouse/inventory/relocate` | 换库位(源库位 → 目标库位) | + +#### 店铺 — 共 **14 个**(首期可再砍) + +| 页面 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| 授权 | POST | `/order/platform-store/list` | 列表 | +| 授权 | POST | `/order/platform-store/auth-url` | OAuth | +| 授权 | POST | `/order/platform-store/save` | 改名等 | +| 授权 | POST | `/order/platform-store/delete` | 删除 | +| 订单 | POST | `/order/platform-store-order/list` | 列表 | +| 订单 | GET | `/order/platform-store-order/detail` | 详情 | +| 订单 | GET | `/order/platform-store-order/summary` | 状态统计(合并多个 count 接口) | +| 订单 | POST | `/order/platform-store-order/sync-status` | 同步 | +| 订单 | POST | `/order/platform-store-order/ready-to-ship` | RTS | +| 订单 | POST | `/order/platform-store-order/match-inventory` | 库存匹配 → `t_order` | +| 订单 | POST | `/order/platform-store-order/fetch-label` | 面单 | +| 订单 | POST | `/order/platform-store-order/toggle-suspend` | 搁置 | +| 订单 | POST | `/order/platform-store-order/delete` | 删除 | + +**入库 `save` 请求(含箱号)** + +```json +{ + "id": 0, + "warehouseId": 1, + "markReference": "MARK-001", + "inboundType": "normal", + "remark": "", + "boxes": [ + { + "boxSeqNo": "1", + "markBoxNo": "BOX-001", + "weightG": 1200, + "lengthCm": 40, + "widthCm": 30, + "heightCm": 20, + "lines": [ + { "skuId": 1001, "skuCode": "SKU-A001", "plannedQty": 50 } + ] + } + ] +} +``` + +**`confirm-receive` 请求要点**:按箱提交实收数量及每行 `binLocationId`,服务端 upsert `C_inventory`。 + +**库存匹配**:按 `C_sku_platform_map` 解析 SKU,从指定库位(或默认库位)扣减 `C_inventory.Qty`;不足则失败;不记流水。 + +--- + +### 4.1 订单 — 店铺授权 `/order/platform-store/*`(完整版参考) + +| 接口 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| 店铺列表 | POST | `/order/platform-store/list` | 分页;筛 `platformCode`、`storeNickname`、授权到期 | +| 授权 URL | POST | `/order/platform-store/auth-url` | 获取 OAuth 跳转地址 | +| OAuth 回调落库 | POST | `/order/platform-store/auth-callback` | 各平台 token 写入 `t_sales_store_token` | +| 店铺详情 | GET | `/order/platform-store/detail` | `id` | +| 改名 | POST | `/order/platform-store/rename` | `id`, `storeNickname` | +| 删除 | POST | `/order/platform-store/delete` | `ids[]` | +| 自动发货开关 | POST | `/order/platform-store/toggle-auto-fulfill` | `ids[]`, `enabled` | +| 到期提醒统计 | GET | `/order/platform-store/expiration-stats` | 即将过期 / 已过期数量 | +| 状态统计 | POST | `/order/platform-store/dashboard-stats` | 按平台汇总店铺与订单数 | + +**列表请求示例** + +```json +{ + "page": 1, + "pageSize": 30, + "platformCode": "shopee", + "storeNickname": "", + "expirationFilter": "normal" +} +``` + +`expirationFilter`:`normal` / `within7days` / `expired`。 + +**列表响应 `items[]` 关键字段**:`id`, `platformCode`, `platformName`, `storeNickname`, `platformAccount`, `siteCountry`, `authStatus`, `authTime`, `tokenExpireTime`, `isAutoFulfill`, `createTime`。 + +**平台子接口**(建议内聚于 `PlatformStoreService`,路径带平台段): + +| 平台 | 路径前缀 | +| --- | --- | +| Shopee | `/order/platform-store/shopee/*` | +| Lazada | `/order/platform-store/lazada/*` | +| TikTok | `/order/platform-store/tiktok/*` | + +--- + +### 4.2 订单 — 店铺订单 `/order/platform-store-order/*` + +| 接口 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| 订单列表 | POST | `/order/platform-store-order/list` | 分页 + 多 Tab 状态 | +| 状态统计 | POST | `/order/platform-store-order/status-count` | 各履约状态数量 | +| 待发货统计 | GET | `/order/platform-store-order/pending-ship-count` | | +| 取消单统计 | GET | `/order/platform-store-order/canceled-count` | | +| 订单详情 | GET | `/order/platform-store-order/detail` | 含 `lines[]`、拆单、草稿 | +| 准备发货 RTS | POST | `/order/platform-store-order/ready-to-ship` | 单条 | +| 批量 RTS | POST | `/order/platform-store-order/batch-ready-to-ship` | | +| 库存匹配下单 | POST | `/order/platform-store-order/match-inventory` | 按 SKU 映射扣库存并创建 `t_order` 草稿 | +| 批量库存匹配 | POST | `/order/platform-store-order/batch-match-inventory` | | +| 同步平台状态 | POST | `/order/platform-store-order/sync-status` | | +| 搁置 / 取消搁置 | POST | `/order/platform-store-order/toggle-suspend` | | +| 删除 | POST | `/order/platform-store-order/delete` | `ids[]` | +| 获取面单 | POST | `/order/platform-store-order/fetch-label` | 返回 `shippingLabelUrl` | +| 更新标签 | POST | `/order/platform-store-order/update-tags` | `id`, `customTags` | +| 快速录单 | POST | `/order/platform-store-order/add-draft` | 写入 `t_sales_store_order_draft` | +| 导出 | POST | `/order/platform-store-order/export` | 异步或同步文件流 | + +**列表请求关键字段** + +```json +{ + "page": 1, + "pageSize": 30, + "platformCode": "shopee", + "fulfillStatus": "pending", + "platformOrderNo": "", + "shippingLabelNo": "", + "storeId": null, + "isSuspended": false, + "orderTimeStart": "2026-01-01", + "orderTimeEnd": "2026-04-01", + "searchType": "orderNo", + "searchKeyword": "" +} +``` + +`searchType`:`orderNo`(平台单号)/ `labelNo`(面单号)/ `whSku`(库内 SKU)。 + +**列表响应 `items[]` 关键字段**:`id`, `storeId`, `storeNickname`, `platformCode`, `platformOrderNo`, `orderCountry`, `totalAmount`, `currency`, `platformOrderTime`, `fulfillStatus`, `fulfillStatusLabel`, `shippingLabelNo`, `shippingLabelUrl`, `isMultiLabel`, `deliveryMethodLabel`, `customTags`, `isSuspended`, `presaleDays`, `lines[]`(含 `platformSku`, `productName`, `quantity`, `isShipExcluded`), `linkedOrderId`。 + +**库存匹配下单逻辑(对齐 WMS `matchSkuInventoryOrder`)** + +1. 校验店铺订单归属与 `fulfillStatus` 允许发货。 +2. 按 `C_sku_platform_map` 解析每行 `MappedSkuId`;未映射行失败。 +3. 按库位扣减 `C_inventory.Qty`(优先默认库位或请求指定 `binLocationId`)。 +4. 调用 OMS `CreateParcelCoreAsync` 创建小包订单草稿,回写 `LinkedOrderId`。 +5. 更新店铺订单 `fulfillStatus`。 + +--- + +### 4.3 仓储 — 我的包裹 `/warehouse/parcel/*` + +| 接口 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| 包裹列表 | POST | `/warehouse/parcel/list` | 按 `lifecycleStatus` Tab | +| 状态统计 | POST | `/warehouse/parcel/status-count` | 各状态数量 | +| 包裹详情 | GET | `/warehouse/parcel/detail` | 含 `items[]` | +| 新增 | POST | `/warehouse/parcel/create` | | +| 编辑 | POST | `/warehouse/parcel/update` | | +| 删除 | POST | `/warehouse/parcel/delete` | `ids[]` | +| 申请入库 | POST | `/warehouse/parcel/apply-storage` | 到仓包裹进入库存流程 | + +**列表请求**:`lifecycleStatus`(`inTransit`/`arrived`/`unclaimed`/`expired`)、`warehouseId`、`trackingNo`、`parcelCategory`、`productName`(模糊搜明细)。 + +**创建请求** + +```json +{ + "warehouseId": 1, + "trackingNo": "SF1234567890", + "carrierName": "顺丰", + "parcelCategory": "single", + "remark": "", + "items": [ + { + "productName": "手机壳", + "quantity": 2, + "imageUrl": "", + "attributeText": "黑色" + } + ] +} +``` + +--- + +### 4.4 仓储 — 我的库存 `/warehouse/inventory/*` + +| 接口 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| 库存汇总列表 | POST | `/warehouse/inventory/list` | 已入库 SKU 维度 | +| 在途列表 | POST | `/warehouse/inventory/in-transit-list` | 已到仓未上架(对齐 WMS `packageList3`) | +| 状态统计 | GET | `/warehouse/inventory/status-count` | 已到仓 / 已入库数量 | +| 库位明细 | GET | `/warehouse/inventory/bin-detail` | 某 SKU 多库位 | +| 上架 | POST | `/warehouse/inventory/putaway` | 包裹或 SKU 上架 | +| 换库位 | POST | `/warehouse/inventory/relocate` | | +| 调整数量 | POST | `/warehouse/inventory/adjust-qty` | 多库位批量调整 | +| 更新尺重 | POST | `/warehouse/inventory/update-dimension` | | +| 库存流水 | POST | `/warehouse/inventory/movement-list` | 分页 | +| 导出 | POST | `/warehouse/inventory/export` | | + +**库存列表请求**:`whSkuCode`, `productName`, `availabilityFilter`(`available`/`replenish`/`all`)、`warehouseId`, `sortBy`(`putawayTime`/`availableQty`)。 + +**列表响应 `items[]`**:`whSkuId`, `whSkuCode`, `skuName`, `availableQty`, `onHandQty`, `frozenQty`, `binLocationCode`, `lengthCm`, `widthCm`, `heightCm`, `weightG`, `putawayTime`, `parcelTrackingNo`(来源包裹)。 + +--- + +### 4.5 仓储 — 我的 SKU `/warehouse/sku/*` + +| 接口 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| SKU 列表 | POST | `/warehouse/sku/list` | 分页 | +| 类型统计 | GET | `/warehouse/sku/type-count` | 普通 / 组合数量 | +| 详情 | GET | `/warehouse/sku/detail` | 含映射、组合子项 | +| 新增 | POST | `/warehouse/sku/create` | | +| 编辑 | POST | `/warehouse/sku/update` | | +| 删除 | POST | `/warehouse/sku/delete` | | +| 批量删除 | POST | `/warehouse/sku/batch-delete` | | +| 批量导入 | POST | `/warehouse/sku/import` | Excel | +| 组合 SKU 导入 | POST | `/warehouse/sku/import-bundle` | | +| 映射详情 | GET | `/warehouse/sku/mapping-detail` | `whSkuId` | +| 批量绑定平台 SKU | POST | `/warehouse/sku/bind-platform-sku` | | +| 导入映射 | POST | `/warehouse/sku/import-mapping` | | +| 打印 SKU 标签 | POST | `/warehouse/sku/print-label` | 返回 PDF URL | + +**列表请求**:`skuCode`, `skuName`, `isBundle`, `mappingStatus`(`mapped`/`unmapped`/`all`), `sortBy`。 + +**列表响应**:`id`, `skuCode`, `skuName`, `skuImageUrl`, `isBundle`, `weightG`, `lengthCm`, `widthCm`, `heightCm`, `referencePrice`, `currency`, `mappingCount`, `onHandQty`, `inboundPendingQty`, `binLocationCode`。 + +--- + +### 4.6 仓储 — 入库预报 `/warehouse/inbound-notice/*` + +| 接口 | 方法 | 路径 | 说明 | +| --- | --- | --- | --- | +| 列表 | POST | `/warehouse/inbound-notice/list` | 分页 | +| 状态统计 | POST | `/warehouse/inbound-notice/status-count` | | +| 详情 | GET | `/warehouse/inbound-notice/detail` | 含 `boxes[].lines[]` | +| 新增 | POST | `/warehouse/inbound-notice/create` | | +| 编辑 | POST | `/warehouse/inbound-notice/update` | 仅 `receiptStatus=forecasted` 可编辑 | +| 删除 | POST | `/warehouse/inbound-notice/delete` | | +| 导入校验 | POST | `/warehouse/inbound-notice/import-validate` | 箱号导入预检 | +| 导入保存 | POST | `/warehouse/inbound-notice/import-save` | | +| 异常信息 | GET | `/warehouse/inbound-notice/exception-detail` | | +| 标记异常 | POST | `/warehouse/inbound-notice/mark-exception` | | +| 取消异常 | POST | `/warehouse/inbound-notice/clear-exception` | | +| 确认收货 | POST | `/warehouse/inbound-notice/confirm-receive` | 客户侧确认到仓 | +| SKU 清点 | POST | `/warehouse/inbound-notice/inspect` | | +| 打印标签 | POST | `/warehouse/inbound-notice/print-label` | PDF | +| 生成单号 | GET | `/warehouse/inbound-notice/next-no` | 可选预取 | + +**创建请求** + +```json +{ + "warehouseId": 1, + "markReference": "MARK-001", + "inboundType": "normal", + "remark": "", + "boxes": [ + { + "boxSeqNo": "1", + "markBoxNo": "BOX-001", + "weightG": 1200, + "lengthCm": 40, + "widthCm": 30, + "heightCm": 20, + "lines": [ + { + "whSkuId": 1001, + "whSkuCode": "SKU-A001", + "plannedQty": 50 + } + ] + } + ] +} +``` + +服务端生成 `noticeNo` = `IN` + SnowflakeId。 + +**列表响应关键字段**:`id`, `noticeNo`, `markReference`, `warehouseId`, `warehouseName`, `inboundType`, `receiptStatus`, `receiptStatusLabel`, `expectedArrivalTime`, `actualArrivalTime`, `skuSummary`, `receivedSkuSummary`, `receiveProgress`, `boxCount`, `receivedBoxCount`, `isException`, `createTime`。 + +--- + +## 5 主业务流程 + +### 5.1 店铺授权 → 拉单 + +```mermaid +sequenceDiagram + participant U as 客户 + participant OMS as OMS API + participant Plat as 电商平台 + + U->>OMS: 获取 auth-url + OMS-->>U: OAuth URL + U->>Plat: 授权 + Plat-->>OMS: auth-callback(code) + OMS->>OMS: 写入 t_sales_store + token + Note over OMS,Plat: 定时任务拉取店铺订单 + OMS->>Plat: 拉单 API + OMS->>OMS: upsert t_sales_store_order +``` + +- 平台订单 **定时同步** + 手动「同步状态」;Token 过期前刷新(各平台 Adapter)。 +- Manual 店铺:无 OAuth,支持手工录入订单(二期)。 + +### 5.2 店铺订单 → 小包发货 + +1. 用户在「店铺订单」筛选 `fulfillStatus=pending`。 +2. 操作「库存匹配」:映射 → 扣库存 → 创建 `t_order`。 +3. 或操作「准备发货」:调平台 RTS API → 更新 `fulfillStatus`。 +4. 获取平台面单 → 可关联 OMS 出库流程。 + +### 5.3 入库预报 → 库存 + +1. 客户维护 `C_sku` → 创建入库预报(`C_inbound_notice` + **箱号** `C_inbound_box` + 箱内行 `C_inbound_box_line`)→ `ReceiptStatus=forecasted`。 +2. 仓库 `confirm-receive`:按箱清点,每行指定 `BinLocationId` → 累加 `C_inventory.Qty` → `completed`。 +3. **不做**清点/上架多态、收货日志表。 + +### 5.4 我的包裹 → 库存 + +1. 客户登记快递单号 → `inTransit`。 +2. 到仓 → `arrived`;`putaway` 指定 `SkuId` + `BinLocationId` → 累加 `C_inventory` → `stored`。 + +--- + +## 6 客户数据隔离 + +与 OMS §4.4.0 对齐,扩展至仓储模块: + +| 规则 | 说明 | +| --- | --- | +| 隔离键 | `effectiveCustomerId` = `t_customer.Id` | +| 列表 | 强制 `CustomerId = effectiveCustomerId` | +| 单条读写 | 先查主表 `CustomerId`,不匹配返回「数据不存在」 | +| 子客户 | 与订单模块策略统一(推荐归并主客户 Id) | +| 关联表 | 通过主表 `OrderId` / `ParcelId` / `InboundNoticeId` 间接隔离 | +| 管理员 | `loginType=0` 可传 `customerId` 查指定客户(与现网订单一致) | + +--- + +## 7 WMS 对照表(实现参考,非字段拷贝) + +| WMS 概念 | WMS 表/字段 | OMS 设计 | +| --- | --- | --- | +| 店铺 | `vip_shop` | `t_sales_store` + `t_sales_store_token` | +| 店铺订单 | `vip_shop_ord` | `t_sales_store_order` | +| 订单明细 | `vip_shop_ord_pro` | `t_sales_store_order_line` | +| 包裹 | `vip_package` | `C_parcel` | +| 包裹明细 | `vip_package_pro` | `C_parcel_item` | +| 库存余额 | `vip_package_inventory` | `C_inventory`(按库位) | +| 库位 | `storage_id` / `storageText` | `C_bin_location` | +| 库存流水 | `wms_stock_record` | `C_stock_movement` | +| 商品 SKU | `wms_goods_sku` | `C_sku` | +| 组合 SKU | `wms_goods_sku_combine` | `C_sku_bundle_item` | +| 平台映射 | `wms_shop_mapping_products_contact` | `C_sku_platform_map` | +| 入库单 | `wms_warehousing_order` | `C_inbound_notice` | +| 入库箱 | `wms_warehousing_box` | `C_inbound_box` | +| 箱内 SKU | `wms_warehousing_box_goods` | `C_inbound_box_line` | +| 收货日志 | `wms_warehousing_order_inbound_log` | `C_inbound_receipt_log` | +| 会员 | `vipId` | `CustomerId` | +| 仓库 | `whseId` | `WarehouseId` → `t_warehouse_address` | + +| WMS 接口前缀 | OMS 接口前缀 | +| --- | --- | +| `/vip/shop/*` | `/order/platform-store/*` | +| `/vip/ord/*` | `/order/platform-store-order/*` | +| `/vip/package/*` | `/warehouse/parcel/*`、`/warehouse/inventory/*` | +| `/wms/warehousing/sku/*` | `/warehouse/sku/*` | +| `/wms/warehousing/order/*` | `/warehouse/inbound/*` | + +--- + +## 8 枚举与常量 + +### 8.1 店铺订单履约状态 `FulfillStatus` + +| 值 | 说明 | WMS 对应 | +| --- | --- | --- | +| `all` | 全部(筛选用) | `0` | +| `pending` | 待处理 | `pending` | +| `toShip` | 待发货 | `toBeShipped` | +| `canceled` | 已取消 | `cancel` | +| `suspended` | 已搁置 | `suspended` | +| `shipped` | 已发货 | `shipped` | +| `completed` | 已完成 | `completed` | + +### 8.2 包裹生命周期 `LifecycleStatus` + +**轻量版(3 态)**:`inTransit` / `arrived` / `stored` + +| 值 | 说明 | WMS `pkgStatus` | +| --- | --- | --- | +| `inTransit` | 待到仓 | `1` | +| `arrived` | 已到仓 | `2` | +| `stored` | 已入库 | — | +| ~~`unclaimed`~~ | 待认领 **〔延后〕** | `3` | +| ~~`expired`~~ | 已到期 **〔延后〕** | `4` | + +### 8.3 库存变动类型 `MovementType` **〔延后,轻量版不建流水表〕** + +| 值 | 说明 | +| --- | --- | +| `inbound` | 入库上架 | +| `allocate` | 订单分配冻结 | +| `release` | 释放冻结 | +| `outbound` | 出库扣减 | +| `adjust` | 人工调整 | +| `relocate` | 换库位 | + +### 8.4 入库预报状态 `ReceiptStatus` + +**轻量版(3 态)**:`forecasted` → `received` → `completed` + +| 值 | 说明 | WMS `adopt` | +| --- | --- | --- | +| `forecasted` | 已预报 | `N` | +| `received` | 已到仓待确认 | `B`/`C` 合并 | +| `completed` | 已入库 | `Y` | +| ~~`inspecting`~~ / ~~`putaway`~~ / ~~`exception`~~ | **〔延后〕** | | + +### 8.5 平台编码 `PlatformCode` + +| 值 | 平台 | +| --- | --- | +| `lazada` | Lazada | +| `shopee` | Shopee | +| `tiktok` | TikTok Shop | +| `temu` | Temu | +| `manual` | 手工店铺 | + +--- + +## 9 实施分期建议 **〔轻量版见 §0.5〕** + +| 阶段 | 范围 | 交付物 | +| --- | --- | --- | +| **M1** | SKU + 入库预报 + 库存余额 | 3 表 + `WarehouseService` 10 个接口 + 2 页 | +| **M2** | 包裹 + 库存只读页 | +2 表 + 6 接口 + 2 页 | +| **M3** | 店铺授权 + 店铺订单 | +3 表 + 2 Service + 2 页 | +| **M4** | 库存匹配 → `t_order` | 打通订单 | **已完成** | + +**完整版分期(v0.1,仅供参考)** + +| 阶段 | 范围 | +| --- | --- | +| P0~P4 | 见原表 | + +--- + +## 10 附录:迁移脚本 + +**一步建表(推荐)** + +``` +sql/migrate_warehouse_module.sql -- 仓储 C_* 9 张 + 店铺 t_sales_* 3 张 +``` + +执行后需在 `Oms.Domain` 中已有对应实体(Step 1 已落地)。 + +--- + +## 11 待决事项(评审时确认) + +1. **子客户订单归属**:与订单模块统一。 +2. **库位维护入口**:`C_bin_location` 放仓储菜单还是系统仓库管理 — 建议 **仓库地址详情页** 或仓储下子页。 +3. **默认库位**:每仓库是否预置一个 `DEFAULT` 库位,简化客户上架。 +4. **包裹是否 M1 必做**:主路径若为入库预报,包裹可 M2。 +5. **平台首期范围**:Shopee / Lazada / TikTok 择几先做。 + +--- + +*文档结束。实现时以 `docs/oms系统设计-050801.md` §3 公共规范与 `docs/rbac系统设计-060801.md` 权限模型为准;若与本文冲突,以评审结论更新本文档版本号。* diff --git a/docs/订单全链路自动化测试方案.md b/docs/订单全链路自动化测试方案.md new file mode 100644 index 0000000..bbe2ce8 --- /dev/null +++ b/docs/订单全链路自动化测试方案.md @@ -0,0 +1,602 @@ +# 订单全链路自动化测试方案 + +> **版本**:v1.0 +> **日期**:2026-07-08 +> **适用范围**:OMS 订单从创建 → 预报 → 入库 → 支付 → 出库 → 轨迹 → 签收(设计态) +> **关联文档**:`oms系统设计-050801.md` §4、§6、§10.3;`物流下单协议.md`;`订单批量处理与异步队列方案0707.md` + +--- + +## 1. 目标与范围 + +### 1.1 目标 + +建立一套**可重复执行、可接入 CI** 的自动化测试流程,覆盖订单主 happy path: + +``` +下单预报 → 入库收货 → 客户支付 → 出库发货 → 轨迹同步 → 签收完成 +``` + +并验证各阶段: + +- **订单状态**(`OrderStatus`)与时间字段(`ReceiveTime` / `PayTime` / `ShipTime` / `SignTime`) +- **费用**(预报 / 入库 / 出库阶段 `t_order_fee`) +- **客户余额与流水**(`t_customer.Balance`、`t_customer_account_flow`) +- **仓储操作记录**(`t_inbound_record` / `t_outbound_record`) +- **轨迹服务联动**(UpsertSmallBag,可 mock) +- **权限与数据范围**(客户只能看到自己的订单) + +### 1.2 当前实现边界(必读) + +| 阶段 | 状态码 | 后端是否已实现 | 自动化策略 | +|------|--------|----------------|------------| +| 小包创建 + 预报计费 | `predeclared` | ✅ | API 断言 | +| 入库扫描 | `pendingPayment` | ✅ | API 断言 | +| 支付 | `pendingShip` | ✅ | API + 余额断言 | +| 出库扫描 | `pendingOnline` | ✅ | API 断言 | +| 运输中 | `shipping` | ❌ 无写入逻辑 | **Phase 2**:mock 轨迹回调或手工 DB 置态 | +| 派送成功(签收) | `deliverySuccess` + `SignTime` | ❌ 无写入逻辑 | **Phase 2**:同上;或 Track 服务 `UpdateOrderStatus` | +| 问题件 / 理赔件 | `problematic` / `claimed` | ✅ | 分支用例 | + +> **结论**:Phase 1 自动化覆盖到 **`pendingOnline`(待上网)** 为「OMS 内闭环」;签收段在 OMS 回写接口落地前,用 **Track 侧断言 + 预留 OMS 状态同步测试桩** 衔接。 + +--- + +## 2. 测试分层架构 + +```mermaid +flowchart TB + subgraph L4["L4 可选 UI E2E"] + UI[Playwright / Cypress
关键页面冒烟] + end + + subgraph L3["L3 API 全链路 E2E(推荐主战场)"] + E2E[OrderLifecycleE2ETests
真实 MySQL + TestServer] + end + + subgraph L2["L2 API 集成"] + INT[SimpleAdmin.Api.IntegrationTests
路由注册 + Mock 依赖] + end + + subgraph L1["L1 单元测试"] + UNIT[Oms.Tests
计费 / 签名 / Batch 治理] + end + + L1 --> L2 --> L3 + L3 -.-> L4 +``` + +| 层级 | 项目位置 | 依赖 | 运行频率 | +|------|----------|------|----------| +| L1 单元 | `oms0414-back/src/Oms.Tests` | 无 DB | 每次 PR | +| L2 集成 | `oms0414-back/src/SimpleAdmin.Api.IntegrationTests` | TestServer + 内存 RBAC | 每次 PR | +| L3 API E2E | **待建** `Oms.E2E.Tests` 或扩展现有 IntegrationTests | Docker MySQL + 可选 RabbitMQ/WireMock | 每日 / 合并前 | +| L4 UI E2E | **待建** `oms0414/e2e/` | 前端 dev + 后端 API | 发版前手动 / 夜间 | + +--- + +## 3. 测试环境与配置 + +### 3.1 基础服务 + +| 组件 | 用途 | 本地 / CI 建议 | +|------|------|----------------| +| MySQL 8.x | 业务库 `oms_test` | `docker compose` 独立库,每次 E2E 前 migrate | +| SimpleAdmin.Api | OMS 后端 | `ASPNETCORE_ENVIRONMENT=Testing` | +| 前端 Vite | UI E2E 可选 | `localhost:5173` | +| RabbitMQ | 批量任务 E2E | 默认 **关闭**;批量专项用例单独 job 开启 | +| WireMock / MockServer | Track、itfx 下游 | E2E 默认 mock,避免外网依赖 | + +### 3.2 后端配置项(`appsettings.Testing.json` 或环境变量) + +```json +{ + "ConnectionStrings": { "Default": "Server=127.0.0.1;Port=3306;Database=oms_test;..." }, + "OrderBatch": { + "RabbitMq": { "Enabled": false } + }, + "Oms": { + "TrackService": { + "Enabled": true, + "BaseUrl": "http://127.0.0.1:9090", + "AppKey": "TEST_KEY", + "AppSecret": "TEST_SECRET", + "TimeoutSeconds": 5 + }, + "Itfx": { + "BaseUrl": "http://127.0.0.1:9091", + "TimeoutSeconds": 5 + } + }, + "App": { "SendStartupNotification": false } +} +``` + +| 配置节 | 测试关注点 | Mock 策略 | +|--------|------------|-----------| +| `Oms:TrackService` | 创建订单后异步 `UpsertSmallBag` | WireMock 返回 200 + 固定 body | +| `Oms:Itfx` | 下游预报转发(可选步骤) | WireMock 或跳过 | +| `OrderBatch:RabbitMq` | 批量支付/入库等 | 主链路用同步 API;批量单独用例开启 | + +### 3.3 数据库初始化顺序 + +```text +1. db.sql # 全量表结构 +2. sql/migrate_*.sql # 增量迁移(issue_template、xhs 等按需) +3. scripts/order_batch_job_tables.sql +4. sql/seed_e2e_order_lifecycle.sql # 【待建】E2E 专用主数据(见 §4) +``` + +--- + +## 4. 主数据 Fixture(测试前置条件) + +自动化执行前,库中须存在以下**稳定可引用**的数据。建议新增 `sql/seed_e2e_order_lifecycle.sql`,所有 E2E 用例共用同一套编码。 + +### 4.1 主数据清单 + +| 类别 | 表 / 模块 | 测试用固定值 | 说明 | +|------|-----------|--------------|------| +| 国家 | `t_country` | `US` / `CN` | 收件国用于分区计价 | +| 客户 | `t_customer` | `customerCode=E2E001`,`Balance >= 10000` | 支付前须余额充足 | +| RBAC 用户 | `user` | 客户主账号,绑定 `E2E001` | 登录拿 JWT | +| 仓库 | `t_warehouse_address` | `warehouseId=9001` | 下单、扫描共用 | +| 销售产品 | `t_sales_product` | `productCode=E2E-SP-01` | 已发布、已绑定规则/价格快照 | +| 服务渠道 | `t_service_channel` | `channelCode=E2E-CH-01` | 排货后可写入订单 | +| 价格 / 分区 | `t_sales_product_price*`、`t_kpi_area*` | 覆盖 US 分区 | 否则创建订单会 `draft` + `PredeclareFailReason` | +| 计重 / 进位 | `t_weight_rule`、`t_weight_rounding` | 匹配 1kg 标准件 | 入库/outbound 计费依赖 | +| 数据权限 | 数据范围 | 测试用户可见 E2E 客户 | 否则列表为空 | + +### 4.2 登录与请求头 + +```http +POST /admin/auth/login +Content-Type: application/json + +{ "userName": "e2e_customer", "password": "..." } +``` + +后续请求: + +```http +Authorization: Bearer {accessToken} +``` + +客户会话下单时 **不传 `customerId`**(由 `OmsSessionHelper` 解析);内部运营账号测入库/出库时用 **运营 RBAC 账号**。 + +### 4.3 推荐双角色 + +| 角色 | 用途 | 权限前缀 | +|------|------|----------| +| `e2e_customer` | 下单、支付、查单 | `Order.PlaceOrder.*`、`Order.MyOrders.*` | +| `e2e_operator` | 入库、出库扫描 | `Operation.InboundScan.*`、`Operation.OutboundScan.*` | + +--- + +## 5. 主流程用例设计(Happy Path) + +### 5.1 流程总览 + +```mermaid +sequenceDiagram + participant C as 客户 API + participant O as OMS OrderService + participant W as 仓储 Operation + participant F as Finance + participant T as Track(Mock) + + C->>O: POST /order/parcel/create + O-->>C: predeclared + serviceNo + O->>T: UpsertSmallBag (async) + + C->>W: POST /operation/inbound/create + W->>O: ApplyReceiveBilling + W-->>C: pendingPayment + ReceiveTime + + C->>O: POST /order/pay + O->>F: DebitOrderPay + O-->>C: pendingShip + PayTime + + C->>W: POST /operation/outbound/create + W->>O: ApplyShipBilling + W-->>C: pendingOnline + ShipTime + + Note over C,T: Phase 2 签收 + T-->>O: (待实现) 状态回写 + O-->>C: deliverySuccess + SignTime +``` + +### 5.2 分步用例表 + +| 步骤 | API | 方法 | 关键入参 | 期望 `OrderStatus` | 期望副作用 | +|------|-----|------|----------|-------------------|------------| +| 0 可选试算 | `/order/price-check` | POST | `productCode`, 件重尺, 收件国 | — | 返回价格 > 0 | +| 1 创建订单 | `/order/parcel/create` | POST | 见 §5.3 | `predeclared` | `t_order_fee` 预报应收;`ServiceNo` 生成 | +| 2 查详情 | `/order/detail` | GET | `id` | `predeclared` | 发件人/收件人/申报齐全 | +| 3 入库 | `/operation/inbound/create` | POST | `waybillNo`, 实重尺 | `pendingPayment` | `ReceiveTime` 非空;入库费 `ChargingStage=inbound` | +| 4 支付 | `/order/pay` | POST | `{ "id": orderId }` | `pendingShip` | `IsPaid=1`, `PayTime`;余额减少;`account_flow` | +| 5 出库 | `/operation/outbound/create` | POST | `waybillNo`, 实重尺 | `pendingOnline` | `ShipTime` 非空;出库费 | +| 6 列表 | `/order/list` | POST | `status=pendingOnline` | — | 包含该 `serviceNo` | +| 7 轨迹 | Mock 校验 | — | — | — | UpsertSmallBag 被调用 1 次 | +| 8 签收 | **Phase 2** | — | — | `deliverySuccess` | `SignTime` 非空 | + +### 5.3 创建订单请求模板(E2E Fixture) + +```json +{ + "requestId": "e2e-{uuid}", + "clientNo": "E2E-CLIENT-{timestamp}", + "productCode": "E2E-SP-01", + "cargoAttribute": "general", + "warehouseId": 9001, + "length": 30, + "width": 20, + "height": 10, + "actualWeight": 1.2, + "quantity": 1, + "receiver": { + "name": "E2E Receiver", + "phone": "13800000001", + "countryCode": "US", + "state": "CA", + "city": "Los Angeles", + "address": "100 Test St", + "postcode": "90001" + }, + "sender": { + "name": "E2E Sender", + "phone": "13900000001", + "countryCode": "CN", + "city": "Shenzhen", + "address": "Test Warehouse" + }, + "items": [ + { + "nameEn": "Test Goods", + "nameCn": "测试商品", + "quantity": 1, + "unitPrice": 10, + "weight": 1.2, + "hsCode": "6109100021" + } + ] +} +``` + +### 5.4 入库 / 出库请求模板 + +```json +// POST /operation/inbound/create +{ + "waybillNo": "{serviceNo}", + "weight": 1.2, + "length": 30, + "width": 20, + "height": 10, + "warehouseId": 9001 +} + +// POST /operation/outbound/create +{ + "waybillNo": "{serviceNo}", + "weight": 1.2, + "length": 30, + "width": 20, + "height": 10, + "warehouseId": 9001 +} +``` + +--- + +## 6. 功能模块与 API 映射 + +| 业务阶段 | 后端 Service | 前端模块 | 路由 | 权限(`pageButtonCatalog`) | +|----------|--------------|----------|------|---------------------------| +| 试算 / 下单 | `OrderService` | 物流下单 | `/order/placeOrder` | `Order.PlaceOrder.*` | +| 订单管理 | `OrderService` | 我的订单 | `/order/myOrders` | `Order.MyOrders.*` | +| 入库 | `InboundRecordService` | 入库扫描 | `/operation/inboundScan` | `Operation.InboundScan.Inbound` | +| 出库 | `OutboundRecordService` | 出库扫描 | `/operation/outboundScan` | `Operation.OutboundScan.Outbound` | +| 客户余额 | `CustomerBalanceMutator` | 客户管理 / 充值 | `/user/customer` | `User.Customer.*` | +| 应收应付 | `FinanceService` | 应收应付 | `/finance/receivablePayable` | `Finance.ReceivablePayable.Query` | +| 账户流水 | `CustomerAccountFlowService` | — | API | — | +| 渠道配置 | `SalesProductService` 等 | 销售产品 / 服务渠道 | `/channel/*` | 各模块 Query/Edit | +| 轨迹推送 | `SmallBagTrackOrderNotifier` | 我的订单-创建轨迹 | — | `Order.MyOrders.CreateTrackOrder` | +| 下游预报 | `OrderService.DownstreamForward` | 转发下游 | — | `Order.MyOrders.ForwardDownstreamCreate` | +| 批量任务 | `OrderBatchJobCoordinator` | 批量任务 | `/order/batchJobs` | `Order.BatchJobs.*` | + +--- + +## 7. 断言检查点(每层必验) + +### 7.1 HTTP 层 + +- 状态码 200(业务错误时 Fake 框架返回统一错误体,需断言 `message` 为空或 success 标志) +- 响应 JSON 关键字段类型与枚举值 + +### 7.2 订单主表 `t_order` + +```sql +SELECT OrderStatus, IsPaid, ReceiveTime, PayTime, ShipTime, SignTime, + PredeclareFailReason, ChannelCode, ChargeableWeight +FROM t_order WHERE ServiceNo = @serviceNo; +``` + +| 步骤后 | OrderStatus | IsPaid | 时间字段 | +|--------|-------------|--------|----------| +| 创建 | `predeclared` | 0 | 全 NULL | +| 入库 | `pendingPayment` | 0 | ReceiveTime 有值 | +| 支付 | `pendingShip` | 1 | PayTime 有值 | +| 出库 | `pendingOnline` | 1 | ShipTime 有值 | +| 签收 | `deliverySuccess` | 1 | SignTime 有值 | + +### 7.3 费用 `t_order_fee` + +- 预报后:存在 `Type=receivable` 且 `ChargingStage` 含 forecast/predeclare +- 入库后:新增 `ChargingStage=inbound` 行(若产品配置入库计费) +- 出库后:新增 `ChargingStage=outbound` 行 +- 支付金额 = 当前应收合计 + +### 7.4 客户财务 + +```sql +SELECT Balance FROM t_customer WHERE Id = @customerId; +SELECT * FROM t_customer_account_flow + WHERE BizType = 'orderPay' AND BizId = @orderId; +``` + +- 支付后:`Balance` 减少额 = 订单应收合计 +- 流水 `Amount` 为负,`BalanceBefore/After` 连贯 + +### 7.5 仓储记录 + +```sql +SELECT * FROM t_inbound_record WHERE WaybillNo = @serviceNo; +SELECT * FROM t_outbound_record WHERE WaybillNo = @serviceNo; +``` + +### 7.6 轨迹 Mock + +- WireMock 收到 `POST /OrderV2/UpsertSmallBag` +- 请求头含 `appKey`、`timestamp`、`sign`(签名算法见 `SmallBagTrackSignHelperTests`) + +--- + +## 8. 负向与分支用例(摘要) + +| 编号 | 场景 | 触发 | 期望 | +|------|------|------|------| +| N01 | 余额不足支付 | 客户 Balance < 应收 | `账户余额不足` | +| N02 | 未入库支付 | 跳过步骤 3 直接 pay | `当前订单状态不可支付` | +| N03 | 未支付出库 | 跳过步骤 4 直接 outbound | `订单未付款,禁止出库` | +| N04 | 重复支付 | pay 两次 | `订单已支付` | +| N05 | 价格未配置 | 错误 productCode | `draft` + `PredeclareFailReason` | +| N06 | 黑名单国家/客户 | 命中黑名单 | 创建失败,不落库或 draft | +| N07 | 拦截单出库 | intercept 后 outbound | 按业务规则拒绝或警告 | +| B01 | 问题件流程 | mark-problematic | `problematic` + `handleStatus=pending` | +| B02 | 处理完成 | handle-status/update | `handleStatus=processed` | +| B03 | 批量支付 | `/order/batch/pay` + RabbitMQ | Job 全部 success(独立 job) | + +--- + +## 9. 自动化实现建议 + +### 9.1 推荐新建项目结构(后端) + +```text +oms0414-back/ + src/ + Oms.E2E.Tests/ # 新建 + Fixtures/ + OrderLifecycleFixture.cs # 登录、种子数据、清理 + WireMockTrackServer.cs + Scenarios/ + OrderLifecycleHappyPathTests.cs + OrderLifecycleNegativeTests.cs + sql/ + seed_e2e_order_lifecycle.sql + assert_order_state.sql + appsettings.E2E.json +``` + +### 9.2 技术选型 + +| 能力 | 库 | +|------|-----| +| API 宿主 | 复用 `SimpleAdminApiTestHost` 或 `WebApplicationFactory` + 真实 MySQL | +| DB 断言 | `Dapper` / 直接 `SqlSugar` 查询 | +| HTTP 客户端 | `HttpClient` + `System.Text.Json` | +| Mock 外服 | `WireMock.Net` | +| 测试框架 | xUnit + FluentAssertions(与现有一致) | + +### 9.3 示例测试类骨架(伪代码) + +```csharp +[Collection("OrderLifecycle")] +public class OrderLifecycleHappyPathTests +{ + [Fact] + public async Task Step01_To_Step05_PendingOnline_ShouldSucceed() + { + var token = await Fixture.LoginAsCustomerAsync(); + var create = await Fixture.Api.PostJsonAsync("/admin/order/parcel/create", body, token); + create.OrderStatus.Should().Be("predeclared"); + var serviceNo = create.ServiceNo; + + await Fixture.Api.PostJsonAsync("/admin/operation/inbound/create", inboundBody, operatorToken); + await Fixture.AssertOrderStatusAsync(serviceNo, "pendingPayment"); + + await Fixture.Api.PostJsonAsync("/admin/order/pay", new { id = create.Id }, token); + await Fixture.AssertOrderStatusAsync(serviceNo, "pendingShip"); + await Fixture.AssertBalanceDebitedAsync(create.CustomerId, create.Id); + + await Fixture.Api.PostJsonAsync("/admin/operation/outbound/create", outboundBody, operatorToken); + await Fixture.AssertOrderStatusAsync(serviceNo, "pendingOnline"); + + Fixture.TrackMock.VerifyUpsertCalledOnce(serviceNo); + } +} +``` + +### 9.4 数据隔离策略 + +| 策略 | 做法 | +|------|------| +| **A 每用例独立 clientNo** | `E2E-{guid}`,不删库,靠唯一键隔离(推荐) | +| **B 事务回滚** | SqlSugar 难包裹跨 HTTP 请求,不推荐 | +| **C 每 job 重建库** | CI 慢但最干净;夜间全量 E2E 使用 | + +--- + +## 10. CI/CD 流水线设计 + +```mermaid +flowchart LR + PR[PR / Push] --> L1[dotnet test Oms.Tests] + L1 --> L2[dotnet test IntegrationTests] + L2 --> E2E{main 分支?} + E2E -->|是| Docker[启动 MySQL + WireMock] + Docker --> Seed[执行 seed_e2e_order_lifecycle.sql] + Seed --> L3[dotnet test Oms.E2E.Tests] + L3 --> Report[测试报告 / 飞书通知] +``` + +### 10.1 GitHub Actions 示例(片段) + +```yaml +jobs: + unit-and-integration: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: dotnet test src/Oms.Tests + - run: dotnet test src/SimpleAdmin.Api.IntegrationTests + + order-lifecycle-e2e: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + services: + mysql: + image: mysql:8.0 + env: + MYSQL_ROOT_PASSWORD: test + MYSQL_DATABASE: oms_test + steps: + - run: mysql -h 127.0.0.1 -uroot -ptest oms_test < db.sql + - run: mysql -h 127.0.0.1 -uroot -ptest oms_test < sql/seed_e2e_order_lifecycle.sql + - run: dotnet test src/Oms.E2E.Tests --filter Category=E2E +``` + +### 10.2 本地一键脚本(建议 `scripts/run-order-e2e.ps1`) + +```powershell +docker compose -f docker-compose.e2e.yml up -d +dotnet test src/Oms.E2E.Tests +docker compose -f docker-compose.e2e.yml down +``` + +--- + +## 11. Phase 2:签收段衔接方案 + +OMS 尚未实现 `shipping` → `deliverySuccess` 回写时,任选其一: + +| 方案 | 说明 | 适用 | +|------|------|------| +| **P2-A Track 侧完成** | 调 `trackApi/Track/Order/UpdateOrderStatus` 置 `isCompleted=true` | 验证轨迹系统闭环 | +| **P2-B 测试专用 API** | 新增 `[TestingOnly] POST /order/test/mark-delivered` | 仅 Testing 环境注册 | +| **P2-C SQL 置态** | E2E 直接 `UPDATE t_order SET OrderStatus='deliverySuccess', SignTime=NOW()` | 临时;不验 API | +| **P2-D 实现正式回调** | Track Webhook → OMS Consumer | 生产方案,纳入同一 E2E | + +**推荐路径**:先 **P2-B** unblock E2E,上线前替换为 **P2-D** 并删除测试 API。 + +--- + +## 12. 实施路线图 + +| 阶段 | 交付物 | 工时估 | +|------|--------|--------| +| **P0** | 本文档 + `seed_e2e_order_lifecycle.sql` | 1d | +| **P1** | `Oms.E2E.Tests` Happy Path(至 pendingOnline) | 2–3d | +| **P1** | WireMock Track + 负向用例 N01–N04 | 1d | +| **P2** | 签收置态 / Webhook + 完整端到签收 | 2d | +| **P3** | Playwright 冒烟(下单页 + 扫描页) | 2d | +| **P3** | CI nightly + 测试报告 | 1d | + +--- + +## 13. 关键代码与文档索引 + +### 后端 + +| 路径 | 说明 | +|------|------| +| `Oms.Domain/OrdersAggregate/Consts/OrderStatusCodes.cs` | 订单状态枚举 | +| `Oms.Application/Services/Orders/OrderService.ParcelBilling.cs` | 创建、入库/出库计费 | +| `Oms.Application/Services/Orders/OrderService.cs` | 支付、列表 | +| `Oms.Application/Services/Operations/InboundRecordService.cs` | 入库 | +| `Oms.Application/Services/Operations/OutboundRecordService.cs` | 出库 | +| `Oms.Application/Shared/CustomerBalanceMutator.cs` | 支付扣款 | +| `Oms.Application/Integrations/SmallBagTrack/` | 轨迹推送 | +| `SimpleAdmin.Api.IntegrationTests/Support/SimpleAdminApiTestHost.cs` | 集成测试宿主 | +| `Oms.Tests/ParcelBillingCalculatorTests.cs` | 计费单元测试 | + +### 前端 + +| 路径 | 说明 | +|------|------| +| `src/constants/orderStatus.ts` | 状态常量 | +| `src/api/order/index.ts` | 订单 API | +| `src/api/operation/index.ts` | 仓储 API | +| `src/views/order/placeOrder/index.vue` | 下单页 | +| `src/views/operation/inboundScan/index.vue` | 入库 | +| `src/views/operation/outboundScan/index.vue` | 出库 | + +### 文档 + +| 路径 | 说明 | +|------|------| +| `docs/oms系统设计-050801.md` | 主设计(§4 订单、§6 操作、§10.3 状态码) | +| `docs/物流下单协议.md` | parcel/create 协议 | +| `docs/订单批量处理与异步队列方案0707.md` | 批量异步 | + +--- + +## 14. 附录:手动冒烟检查清单(5 分钟) + +自动化未就绪时,可按此手工验证主链路: + +- [ ] 客户登录,余额 ≥ 100 +- [ ] 销售产品 `E2E-SP-01` 已发布且 US 有价格 +- [ ] `POST /order/parcel/create` → 返回 `predeclared` +- [ ] `POST /operation/inbound/create` → 订单变 `pendingPayment` +- [ ] `POST /order/pay` → `pendingShip`,余额减少 +- [ ] `POST /operation/outbound/create` → `pendingOnline` +- [ ] `GET /order/detail` → `ReceiveTime`、`PayTime`、`ShipTime` 均有值 +- [ ] (可选)Track Mock 日志有 UpsertSmallBag + +--- + +## 15. 已落地实现(2026-07-08) + +| 交付物 | 路径 | +|--------|------| +| E2E 主数据种子 | `oms0414-back/sql/seed_e2e_order_lifecycle.sql` | +| E2E 测试项目 | `oms0414-back/src/Oms.E2E.Tests/` | +| Happy Path 用例 | `Scenarios/OrderLifecycleHappyPathTests.cs` | +| 一键脚本 | `oms0414-back/scripts/run-order-e2e.ps1` | + +**运行方式:** + +```powershell +$env:OMS_E2E_ENABLED = "1" +$env:OMS_E2E_CONNECTION = "Server=127.0.0.1;Port=3306;Database=oms;Uid=root;Pwd=你的密码;CharSet=utf8mb4;" +cd oms0414-back +.\scripts\run-order-e2e.ps1 +``` + +未设置 `OMS_E2E_ENABLED` 时,E2E 用例自动跳过(不失败)。 + +--- + +**维护说明**:OMS 实现签收回写后,更新 §1.2 边界表、§5 步骤 8、§11,并将 Phase 2 用例并入 P1 必跑集。 diff --git a/docs/订单批量处理与异步队列方案0707.md b/docs/订单批量处理与异步队列方案0707.md new file mode 100644 index 0000000..d9d0320 --- /dev/null +++ b/docs/订单批量处理与异步队列方案0707.md @@ -0,0 +1,664 @@ +# 订单批量处理与异步队列方案 + +> **文档定位**:梳理 OMS 后端现有订单批量相关 API、执行模式与可复用资产,并给出统一异步队列改造建议。 +> **对照仓库**:`C:\Users\wilso\Desktop\oms0414-back`(`SimpleAdmin.sln`) +> **前端对照**:`E:\oms0414\src\views\order\myOrders\index.vue` +> **关联文档**:`docs/oms系统设计-050801.md`(订单章)、`docs/rbac系统设计-060801.md`(权限) +> **编写日期**:2026-07-07 +> **技术决策**:**选用 RabbitMQ** 作为订单批量异步队列方案(v2.0) + +--- + +## 1 导读 + +### 1.1 这份文档解决什么问题? + +1. **盘点**当前后端所有「批量处理订单」相关 HTTP 接口(含原生批量与前端循环伪批量)。 +2. **说明**各接口入参/出参、Service 实现位置、同步/异步执行方式。 +3. **指出**现有最接近队列的组件(`t_order_task`、`SmallBagTrackOrderNotifier`)及其局限。 +4. **建议**按业务类型划分异步队列、统一批量 Job API 草案与落地优先级。 +5. **定义**基于 **RabbitMQ** 的交换机/队列拓扑、消息契约、Consumer 与 Fake 框架集成方式(**已定稿**)。 + +### 1.2 技术决策 + +| 项 | 决策 | +| --- | --- | +| 消息中间件 | **RabbitMQ** | +| .NET 接入 | 优先复用 Fake 生态 **`Fake.RabbitMQ`**(连接池/通道池);订单 Job 使用 **Work Queue 模式** 自建 Publisher/Consumer | +| 与 `Fake.EventBus.RabbitMQ` 关系 | 事件总线用于**跨模块集成事件**(如 Job 完成通知);**订单子任务投递不走 EventBus**,走专用 Work Queue | +| 状态持久化 | MySQL **`t_order_batch_job` / `t_order_batch_job_item`** 为权威进度;MQ 仅负责调度与重试 | +| 宿主部署 | `SimpleAdmin.Api` 进程内注册 Consumer(`IHostedService`);后期可拆独立 Worker 项目 | + +### 1.3 现状结论(摘要) + +| 维度 | 现状 | +| --- | --- | +| API 暴露 | `OrderService`(partial class)上 `[HttpPost]` / `[HttpGet]`,Fake 动态 API,**无手写 Controller** | +| 原生批量 API | 异常件 3 个 + 小包 `batch-create` + Excel 导入 + 条件导出,共 **5 类** | +| 伪批量 | My Orders 页 **8 个单票 API**,前端 `for` 循环逐条调用 | +| 队列基础设施 | **规划 RabbitMQ**(项目基线已约定 MQ,见 `oms0414-back/开发复刻说明.md`);当前代码**尚未引用** `Fake.RabbitMQ` | +| 轻量异步 | `SmallBagTrackOrderNotifier` 使用 `Task.Run`(无持久化、无重试) | +| 任务表 | `t_order_task` 记录 Excel 导入进度,但处理仍在 **HTTP 请求内同步完成** | +| 权限 | 前端 `Order.MyOrders.*`;**后端 API 未做细粒度 PermissionCode 校验** | + +--- + +## 2 接口总览 + +```mermaid +flowchart LR + subgraph api [SimpleAdmin.Api] + HTTP["/order/batch/jobs"] + OS[OrderService] + end + + subgraph db [MySQL] + JOB[t_order_batch_job] + ITEM[t_order_batch_job_item] + end + + subgraph rmq [RabbitMQ] + EX["exchange: oms.order.batch"] + QD["queue: order.batch.integration"] + QA["queue: order.batch.account"] + QB["queue: order.batch.state"] + QC["queue: order.batch.exception"] + QE["queue: order.batch.document"] + QF["queue: order.batch.create"] + DLX["DLX: oms.order.batch.dlx"] + end + + subgraph consumers [Consumers IHostedService] + CD[IntegrationConsumer] + CA[AccountConsumer] + CB[StateConsumer] + CC[ExceptionConsumer] + CE[DocumentConsumer] + CF[CreateConsumer] + end + + HTTP --> JOB + HTTP --> EX + EX --> QD & QA & QB & QC & QE & QF + QD & QA & QB & QC & QE & QF --> consumers + consumers --> ITEM + consumers --> OS + QD & QA & QB & QC & QE & QF -.失败.-> DLX +``` + +### 2.1 分类一览(改造后目标) + +```mermaid +flowchart TB + subgraph native [原生批量 API] + EP["/order/mark-problematic
/order/mark-claimed
/order/handle-status/update"] + PCB["/order/parcel/batch-create"] + UP["/order/upload + task/*"] + EX["/order/export"] + end + + subgraph pseudo [伪批量 - 前端循环单票 API] + PAY["/order/pay"] + PD["/order/pre-declare"] + INT["/order/intercept / cancel-intercept"] + DEL["/order/delete"] + PRT["/order/print"] + TRK["/order/track-upsert-small-bag"] + DS["/order/downstream-forward-create-one"] + end + + subgraph svc [OrderService 同步处理] + OS[OrderService partial] + end + + subgraph async_hint [现有轻量异步] + OT[t_order_task 仅记录] + STN[SmallBagTrackOrderNotifier Task.Run] + end + + native --> OS + pseudo --> OS + UP --> OT + PCB --> STN +``` + +### 2.2 原生批量 API 清单 + +| 路由 | 方法 | Service 方法 | 文件 | 批量语义 | 上限 | 执行模式 | +| --- | --- | --- | --- | --- | --- | --- | +| `/order/mark-problematic` | POST | `MarkProblematicAsync` | `OrderService.Exception.cs` | `List OrderIds` | 200 | 同步 foreach,部分成功 | +| `/order/mark-claimed` | POST | `MarkClaimedAsync` | 同上 | `List OrderIds` | 200 | 同上 | +| `/order/handle-status/update` | POST | `UpdateHandleStatusAsync` | 同上 | `List OrderIds` | 200 | 同上(仅 `processed`) | +| `/order/parcel/batch-create` | POST | `BatchCreateParcelAsync` | `OrderService.cs` | `List` | 2000 | 同步 for,逐条明细 | +| `/order/upload` | POST | `UploadAsync` → `ImportOrdersAsync` | `OrderService.Helpers.cs` | Excel 多行 | — | 同步逐行 + 写 `OrderTask` | +| `/order/task/list` | GET | `GetTaskListAsync` | `OrderService.Helpers.cs` | 查询导入任务 | — | 只读 | +| `/order/task/detail` | GET | `GetTaskDetailAsync` | 同上 | 含失败行 | — | 只读 | +| `/order/export` | POST | `ExportAsync` | `OrderService.cs` | 筛选条件全量 | — | 同步生成 xlsx | + +### 2.3 伪批量 API 清单(单票入参,前端循环) + +| 路由 | 方法 | Service 方法 | 文件 | 业务特点 | 前端权限码(参考) | +| --- | --- | --- | --- | --- | --- | +| `/order/pay` | POST | `PayAsync` | `OrderService.cs` | **扣客户余额**,需事务/幂等 | `Order.MyOrders.Pay` | +| `/order/pre-declare` | POST | `PreDeclareAsync` | 同上 | 改订单状态 | `Order.MyOrders.PreDeclare` | +| `/order/intercept` | POST | `InterceptAsync` | 同上 | `IsIntercept=1` | `Order.MyOrders.Intercept` | +| `/order/cancel-intercept` | POST | `CancelInterceptAsync` | 同上 | `IsIntercept=0` | `Order.MyOrders.CancelIntercept` | +| `/order/delete` | POST | `DeleteAsync` | 同上 | 软删 + 物理删 | `Order.MyOrders.Delete` | +| `/order/print` | POST | `PrintAsync` | `OrderService.Helpers.cs` | 生成打印 HTML | `Order.MyOrders.Print` / `BatchPrint` | +| `/order/track-upsert-small-bag` | POST | `TrackUpsertSmallBagAsync` | `OrderService.ParcelBilling.cs` | HTTP 调轨迹服务 | `Order.MyOrders.CreateTrack` | +| `/order/downstream-forward-create-one` | POST | `DownstreamForwardCreateOneAsync` | `OrderService.DownstreamForward.cs` | HTTP 调下游 itfx | `Order.MyOrders.ForwardDownstream` | + +**公共入参** `OrderActionInput`: + +```csharp +public class OrderActionInput +{ + [Required] public int Id { get; set; } + [StringLength(64)] public string? RequestId { get; set; } +} +``` + +**辅助只读**: + +| 路由 | 方法 | 说明 | +| --- | --- | --- | +| `/order/downstream-create-one-body` | GET | 预览下游请求体,不实际转发 | + +### 2.4 单票编辑类 API(详情抽屉,非列表批量) + +| 路由 | 方法 | Service 方法 | 文件 | +| --- | --- | --- | --- | +| `/order/update` | POST | `UpdateOrderDetailAsync` | `OrderService.OrderEdit.cs` | +| `/order/weight/update` | POST | `UpdateOrderWeightsAsync` | 同上 | +| `/order/fee/recalculate-receivable` | POST | `RecalculateReceivableFeesAsync` | 同上 | +| `/order/fee/recalculate-payable` | POST | `RecalculatePayableFeesAsync` | 同上 | +| `/order/fee/add` | POST | `AddOrderFeeAsync` | 同上 | +| `/order/parcel/create` | POST | `CreateParcelAsync` | `OrderService.cs` / `ParcelBilling.cs` | + +### 2.5 非 OrderIds 的「批量数据处理」 + +| 路由 | 方法 | 说明 | +| --- | --- | --- | +| `/order/price-check` | POST | 多产品 × 多仓库运费试算,同步嵌套循环 | +| `/order/list` | POST | 分页列表 | +| `/order/status-counts` | GET | 状态 Tab 计数 | + +--- + +## 3 DTO 与出参模型 + +### 3.1 异常件批量(推荐复用为队列 Job 汇总出参) + +**文件**:`Oms.Application/Dtos/Orders/OrderExceptionDtos.cs` + +```csharp +// 统一批量出参 +public class OrderBatchActionResultOutput +{ + public int SuccessCount { get; set; } + public List Failures { get; set; } = []; +} + +public class OrderBatchActionFailureOutput +{ + public int OrderId { get; set; } + public string? ServiceNo { get; set; } + public string Reason { get; set; } = string.Empty; +} + +// 问题件 +public class OrderMarkProblematicInput +{ + public List OrderIds { get; set; } = []; + public int? IssueTemplateId { get; set; } + public string? IssueType { get; set; } + public string? Title { get; set; } + public string? Content { get; set; } + public string? Remark { get; set; } +} + +// 理赔件 +public class OrderMarkClaimedInput +{ + public List OrderIds { get; set; } = []; + public string? ClaimType { get; set; } + public decimal? ClaimAmount { get; set; } + public string? ClaimCurrency { get; set; } + public string? ClaimReason { get; set; } + public string? Remark { get; set; } +} + +// 标记已处理 +public class OrderHandleStatusUpdateInput +{ + public List OrderIds { get; set; } = []; + public string? HandleStatus { get; set; } + public string? Remark { get; set; } +} +``` + +**内部约束**:`MaxExceptionBatchSize = 200`(`OrderService.Exception.cs`)。 + +### 3.2 小包批量创建 + +**文件**:`Oms.Application/Dtos/Orders/OrderParcelBatchCreateInput.cs` 等 + +- **入参**:`OrderParcelBatchCreateInput` 继承 `List`,单条结构与 `/order/parcel/create` 一致。 +- **出参**:`OrderParcelBatchCreateOutput { BatchNo, SuccessCount, FailCount, Items[] }` +- **上限**:`ParcelBatchMaxCount = 2000`(`OrderService.ParcelBilling.cs`) + +### 3.3 Excel 导入 + +| DTO | 字段 | +| --- | --- | +| `OrderUploadInput` | `File` (IFormFile), `TemplateId` | +| `OrderUploadOutput` | `TaskId` | +| `OrderTaskListInput` | 分页查询参数 | +| `OrderTaskOutput` / `OrderTaskDetailOutput` | 任务汇总 + 失败明细 `FailList` | + +### 3.4 条件导出 + +| DTO | 字段 | +| --- | --- | +| `OrderExportInput` | `status`, `keyword`, `createTimeStart`, `createTimeEnd` | +| `OrderExportOutput` | `downloadUrl`, `expireAt`(24h 过期) | + +--- + +## 4 现有执行模式详解 + +### 4.1 异常件批量(已实现部分成功) + +**调用链**: + +``` +MarkProblematicAsync / MarkClaimedAsync / UpdateHandleStatusAsync + → NormalizeOrderIds(去重、非空、≤200) + → ExecuteProblematicBatchAsync / ExecuteExceptionBatchAsync + → 逐条 try/catch,成功 SuccessCount++,失败写入 Failures +``` + +**问题件单条逻辑**:`OrderExceptionWorkflowService.TryMarkProblematicAsync`(`Issues/OrderExceptionWorkflowService.cs`),含通知(`OrderIssueNotificationService`)。 + +### 4.2 小包批量创建 + +``` +BatchCreateParcelAsync + → 生成 BatchNo + → for each OrderParcelCreateInput + → CreateParcelCoreAsync(预报、计费、落库) + → 成功则 EnqueueSmallBagTrackUpsertAsync(轨迹) + → 返回逐条 Items 明细 +``` + +### 4.3 Excel 导入(有任务表,非真异步) + +``` +UploadAsync → ImportOrdersAsync + → Insert OrderTask(Status=processing) + → foreach Excel 行 + → CreateImportOrderAsync 或记录 OrderTaskFail + → 更新 task Quantity / SuccessCount / FailCount / Status=completed + → 返回 { taskId } +``` + +**局限**:整个导入阻塞当前 HTTP 请求;`Status=processing` 仅为记录,无独立 Consumer。 + +### 4.4 轨迹轻量异步(现有唯一 fire-and-forget) + +**文件**:`Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs` + +```csharp +public void Enqueue(SmallBagTrackUpsertRequest request) +{ + _ = Task.Run(async () => + { + using var scope = scopeFactory.CreateScope(); + var client = scope.ServiceProvider.GetRequiredService(); + await client.UpsertAsync(request); + }); +} +``` + +**性质**:单票、内存队列、无持久化、无重试、进程重启即丢失。 + +### 4.5 前端伪批量行为 + +**文件**:`src/views/order/myOrders/index.vue` + +- 勾选多行后,对 `pay` / `pre-declare` / `intercept` 等 **逐条 POST** `OrderActionInput`。 +- 支付等操作:**任一失败即中断**,无部分成功汇总(与异常件 API 不同)。 +- 批量打印 / 轨迹 / 下游:循环调用后前端汇总结果弹窗。 + +--- + +## 5 现有基础设施盘点 + +| 组件 | 是否存在 | 说明 | +| --- | --- | --- | +| RabbitMQ Work Queue | ❌ 未接入 | **本期建设** | +| `Fake.RabbitMQ` | ❌ 未引用 | 连接池/通道池,见 `SPEC.md` §9.3 | +| `Fake.EventBus.RabbitMQ` | ❌ 未引用 | 可选,用于 Job 完成等集成事件 | +| 订单专用 `IHostedService` | ❌ | 无 | +| `BackgroundService` | ✅ 1 个 | 仅 `XhsScheduledPublishWorker`(小红书定时发布) | +| `Task.Run` | ✅ | 轨迹 UpsertSmallBag、导出文件清理等 | +| `t_order_task` | ✅ | 导入任务记录 + `t_order_task_fail` 失败行 | +| `SmallBagTrackOrderNotifier` | ✅ | 内存 fire-and-forget | + +### 5.1 OrderTask 实体(可演进为通用批量 Job 表) + +**表**:`t_order_task` +**实体**:`Oms.Domain/OrdersAggregate/Entities/OrderTask.cs` + +| 字段 | 说明 | +| --- | --- | +| `TaskName` | 如 `批量下单_yyyyMMddHHmmss` | +| `Quantity` | 总条数 | +| `SuccessCount` / `FailCount` | 成功/失败计数 | +| `Status` | `processing` → `completed` | +| `TemplateId` | Excel 模板 Id | +| `CustomerId` | 客户归属 | + +**演进建议**:扩展 `Action`、`PayloadJson`、`StartedAt`、`FinishedAt`,或新建 `t_order_batch_job` 与之并存。 + +--- + +## 6 RabbitMQ 队列分组(与业务 Action 映射) + +按 **业务风险 + 耗时 + 外部依赖** 划分 **6 条业务队列** + **1 条死信队列**: + +| 队列组 | RabbitMQ Queue | Routing Key | 包含 Action | 并发建议 | Prefetch | +| --- | --- | --- | --- | --- | --- | +| **D. 外部集成** | `oms.order.batch.integration` | `integration.*` | `track-upsert-small-bag`, `downstream-forward-create-one` | 中(限流防打爆下游) | 5 | +| **F. 订单创建** | `oms.order.batch.create` | `create.*` | `parcel-create`, `import-row` | 中 | 10 | +| **A. 账务** | `oms.order.batch.account` | `account.*` | `pay` | **低**(按 CustomerId 串行) | 1 | +| **B. 状态变更** | `oms.order.batch.state` | `state.*` | `pre-declare`, `intercept`, `cancel-intercept`, `delete`, `handle-status-update` | 高 | 20 | +| **C. 异常工作流** | `oms.order.batch.exception` | `exception.*` | `mark-problematic`, `mark-claimed` | 中 | 10 | +| **E. 文档生成** | `oms.order.batch.document` | `document.*` | `print`, `export` | 低 | 3 | +| **死信** | `oms.order.batch.dlx` | — | 超过最大重试的子任务 | — | — | + +**Exchange**:`oms.order.batch`(类型 **topic**,持久化 `durable=true`)。 + +### 6.1 落地顺序建议 + +1. **D(外部集成)** — 轨迹、下游预报最阻塞 HTTP,且已有 `SmallBagTrackOrderNotifier` 可替换为 Publisher。 +2. **F(创建/导入)** — `OrderTask` 表与失败明细已就绪,补 Worker 即可真异步。 +3. **A(支付)** — 资金类须严格幂等与对账。 +4. **B / C / E** — 按产品优先级迭代。 + +--- + +## 7 统一批量 Job API 草案 + +### 7.1 路由设计 + +| 路由 | 方法 | 说明 | +| --- | --- | --- | +| `/order/batch/jobs` | POST | 创建批量任务,写 DB 并 Publish 到 RabbitMQ,立即返回 `jobId` | +| `/order/batch/jobs/{id}` | GET | 查询进度与汇总结果 | +| `/order/batch/jobs/{id}/items` | GET | 逐条明细(成功/失败/进行中) | +| `/order/batch/jobs/{id}/cancel` | POST | 取消未执行子任务(可选) | +| `/order/batch/jobs/{id}/retry-failed` | POST | 将 failed 子任务重新 Publish(可选) | + +### 7.2 入参草案 + +```csharp +public class OrderBatchJobCreateInput +{ + /// + /// pay | pre-declare | intercept | cancel-intercept | delete | + /// print | track-upsert-small-bag | downstream-forward-create-one | + /// mark-problematic | mark-claimed | handle-status-update | export | ... + /// + public string Action { get; set; } = string.Empty; + + public List OrderIds { get; set; } = []; + + public JsonElement? Payload { get; set; } + public string? RequestId { get; set; } +} +``` + +### 7.3 出参草案 + +```csharp +public class OrderBatchJobOutput +{ + public long JobId { get; set; } + public string Action { get; set; } = string.Empty; + public string Status { get; set; } = string.Empty; + public int Total { get; set; } + public int SuccessCount { get; set; } + public int FailCount { get; set; } + public DateTime? StartedAt { get; set; } + public DateTime? FinishedAt { get; set; } +} +``` + +单条明细复用 `OrderBatchActionFailureOutput`,扩展 `Status`:`pending` / `running` / `success` / `failed`。 + +--- + +## 8 RabbitMQ 实施方案(已定稿) + +### 8.1 为何选 RabbitMQ + +| 能力 | 说明 | +| --- | --- | +| 持久化队列 | 进程重启不丢任务(配合 `delivery_mode=2`) | +| 死信 + 延迟重试 | 业务失败与系统失败分离治理 | +| 多队列隔离 | 支付、外部 HTTP、导入互不阻塞 | +| 水平扩展 | 多 API/Worker 实例共享 Consumer | +| 与项目基线一致 | `开发复刻说明.md` 已约定 RabbitMQ;Fake 提供 `Fake.RabbitMQ` 连接池 | + +**不采用 Hangfire / DB 轮询的原因**:订单批量含大量外部 HTTP 与长耗时导入,需要独立队列削峰与跨实例消费;DB 轮询难以优雅做按客户串行与 DLX。 + +### 8.2 NuGet 与模块依赖 + +在 `SimpleAdmin.Api` / `Oms.Application` 增加: + +```xml + + + +``` + +模块依赖(`OmsApplicationModule` 或新建 `OmsRabbitMqModule`): + +```csharp +[DependsOn(typeof(FakeRabbitMqModule))] +public class OmsRabbitMqModule : FakeModule { } +``` + +### 8.3 配置(appsettings / Consul) + +```json +{ + "RabbitMQ": { + "Connections": { + "Default": { + "HostName": "rabbitmq", + "Port": 5672, + "UserName": "oms", + "Password": "***", + "VirtualHost": "/oms" + } + } + } +} +``` + +队列声明在应用启动时由 `OrderBatchQueueInitializer`(`IHostedService`)执行:创建 Exchange、6 条业务 Queue、DLX、绑定关系。 + +### 8.4 消息契约 + +**队列消息体** `OrderBatchJobMessage`(JSON,Newtonsoft 驼峰): + +```csharp +public class OrderBatchJobMessage +{ + public long JobId { get; set; } + public long JobItemId { get; set; } + public string Action { get; set; } = string.Empty; // pay, delete, track-upsert-small-bag, ... + public int OrderId { get; set; } + public int? CustomerId { get; set; } // A 组串行键 + public string? PayloadJson { get; set; } // Action 专用参数 + public int OperatorUserId { get; set; } + public string MessageId { get; set; } = string.Empty; // 幂等键 + public int RetryCount { get; set; } +} +``` + +**发布流程**: + +``` +POST /order/batch/jobs + → 写 t_order_batch_job + items(status=pending) + → 按 Action 映射 routingKey,逐条 Publish 到 oms.order.batch + → 立即返回 { jobId } +``` + +**消费流程**: + +``` +Consumer 收到消息 + → 查 item 是否已成功(幂等跳过) + → item.status=running + → IOrderBatchActionExecutor.ExecuteAsync(message) + → 成功:item.status=success,更新 job 计数 + → 业务失败:item.status=failed + reason,ACK + → 系统失败:NACK requeue;RetryCount>=3 → DLX + → job 全部终态后 status=completed +``` + +### 8.5 与现有组件的替换关系 + +| 现有 | 改造后 | +| --- | --- | +| `SmallBagTrackOrderNotifier`(`Task.Run`) | Publish 到 `oms.order.batch.integration`,routingKey=`integration.track-upsert` | +| `ImportOrdersAsync` 同步 foreach | 上传存文件/OSS → 写 job → 每行一条消息到 `oms.order.batch.create` | +| 前端 My Orders 循环 `pay` 等 | 统一 `POST /order/batch/jobs`,轮询 `GET /order/batch/jobs/{id}` | +| 异常件 API `mark-problematic` 等 | **兼容期保留同步 API**;新增 `async=true` 或独立 Job API 走 MQ | + +### 8.6 重试与死信策略 + +| 场景 | 策略 | +| --- | --- | +| 下游 HTTP 超时/5xx | NACK + requeue,指数退避(`x-message-ttl` + DLX 延迟队列,或 Consumer 内 `Task.Delay` 后重发) | +| 业务校验失败(已支付、状态不允许) | 记 failed,**ACK 不重试** | +| 消息重复消费 | `MessageId` + DB 唯一约束,已 success 则直接 ACK | +| DLX 堆积 | 告警 + 管理端「重新投递」接口 | + +建议队列参数: + +``` +x-dead-letter-exchange: oms.order.batch.dlx +x-dead-letter-routing-key: dead +``` + +### 8.7 部署拓扑 + +```mermaid +flowchart TB + subgraph prod [生产环境] + API1[SimpleAdmin.Api 实例 1] + API2[SimpleAdmin.Api 实例 2] + RMQ[RabbitMQ Cluster] + MySQL[(MySQL)] + end + + API1 & API2 -->|Publish/Consume| RMQ + API1 & API2 --> MySQL + FE[oms0414 前端] -->|创建 Job / 轮询进度| API1 +``` + +- **第一期**:Consumer 与 API 同进程(`IHostedService`),减少运维复杂度。 +- **第二期**:拆 `Oms.OrderWorker` 独立控制台项目,仅引用 `Oms.Application` + Consumers。 + +### 8.8 本地开发 + +`docker-compose` 增加 RabbitMQ 服务(管理台 15672): + +```yaml +rabbitmq: + image: rabbitmq:3.13-management + ports: + - "5672:5672" + - "15672:15672" + environment: + RABBITMQ_DEFAULT_USER: oms + RABBITMQ_DEFAULT_PASS: oms123 + RABBITMQ_DEFAULT_VHOST: /oms +``` + +### 8.9 Consumer 执行原则 + +1. **复用现有 Service**:`IOrderBatchActionExecutor` 按 `action` 分发,内部调用抽离后的单条逻辑。 +2. **幂等**:`MessageId = {jobId}:{orderId}:{action}`;DB 唯一键 `(JobId, OrderId, Action)`;支付额外校验 `IsPaid`。 +3. **部分成功**:业务失败 ACK 并写 `failed`;系统失败 NACK requeue,超次进 DLX。 +4. **并发**:A 组 `prefetch=1` + `customerId` 串行;D 组全局限流。 +5. **可观测**:日志带 `JobId/OrderId/Action`;可选 `OrderBatchJobCompletedEto` 走 `Fake.EventBus.RabbitMQ`。 + +--- + +## 9 关键文件索引(规划新增) + +| 文件(规划路径) | 职责 | +| --- | --- | +| `Oms.Application/Messaging/OrderBatchJobMessage.cs` | MQ 消息契约 | +| `Oms.Application/Messaging/IOrderBatchJobPublisher.cs` | Publish 抽象 | +| `Oms.Application/Messaging/OrderBatchQueueInitializer.cs` | 启动声明 Exchange/Queue | +| `Oms.Application/Workers/OrderBatch/*Consumer.cs` | 6 组 RabbitMQ Consumer | +| `Oms.Application/Services/Orders/Batch/IOrderBatchActionExecutor.cs` | Action 执行分发 | +| `Oms.Application/Services/Orders/OrderService.cs` | pay/delete/export/batch-create/upload 等主 API | +| `Oms.Application/Services/Orders/OrderService.Exception.cs` | 原生 `OrderIds` 批量异常件 API | +| `Oms.Application/Services/Orders/OrderService.ParcelBilling.cs` | 小包创建、轨迹同步 | +| `Oms.Application/Services/Orders/OrderService.DownstreamForward.cs` | 下游预报转发 | +| `Oms.Application/Services/Orders/OrderService.Helpers.cs` | Excel 导入、打印、任务查询 | +| `Oms.Application/Integrations/SmallBagTrack/SmallBagTrackOrderNotifier.cs` | 待替换为 MQ Publisher | +| `Oms.Domain/OrdersAggregate/Entities/OrderBatchJob.cs` | Job 实体(规划) | +| `src/views/order/myOrders/index.vue` | 前端伪批量循环(待改 Job API) | + +--- + +## 10 与主设计文档的关系 + +- 订单状态机、费用、模板字段详见 **`docs/oms系统设计-050801.md` 第 4 章**。 +- 客户隔离、`CustomerId` 解析见 **OMS 设计 §1.4** 与 **RBAC 设计文档**。 +- Fake 框架 RabbitMQ 能力见 **`oms0414-back/SPEC.md` §9.3**(`Fake.RabbitMQ`、`Fake.EventBus.RabbitMQ`)。 + +--- + +## 11 后续工作清单(RabbitMQ 实施) + +### 阶段一:基础设施(D 组) + +- [ ] `docker-compose` / 生产环境部署 RabbitMQ(vhost `/oms`) +- [ ] 引用 `Fake.RabbitMQ`,配置 `RabbitMQ:Connections:Default` +- [ ] 新建 `OmsRabbitMqModule`、`OrderBatchQueueInitializer` +- [ ] 新建 `t_order_batch_job` / `t_order_batch_job_item` 表 +- [ ] 实现 `IOrderBatchJobPublisher` + `OrderBatchJobMessage` +- [ ] 实现 `IntegrationBatchConsumer`(轨迹、下游预报) +- [ ] 替换 `SmallBagTrackOrderNotifier` 为 MQ Publish + +### 阶段二:创建与导入(F 组) + +- [ ] `/order/upload` 改为上传落库 + 按行入队 `oms.order.batch.create` +- [ ] `parcel/batch-create` 改为创建 Job 后异步消费 +- [ ] 复用/扩展 `OrderTask` 与 `OrderBatchJob` 关系(如需兼容旧前端) + +### 阶段三:统一 Job API + 前端 + +- [ ] 新增 `/order/batch/jobs` 系列 API +- [ ] 前端 My Orders 批量操作改 Job API + 进度轮询 +- [ ] 实现 B/C/E/A 组 Consumer 与 `IOrderBatchActionExecutor` + +### 阶段四:治理与测试 + +- [ ] DLX 监控告警、`retry-failed` 管理接口 +- [ ] 补充 `SimpleAdmin.Api.IntegrationTests`(Publish → Consume → DB 状态) +- [ ] 可选:拆 `Oms.OrderWorker` 独立进程 + +--- + +*文档版本:v2.0 | 技术决策:RabbitMQ | 2026-07-07* diff --git a/scripts/scan-report.txt b/scripts/scan-report.txt new file mode 100644 index 0000000..9935057 --- /dev/null +++ b/scripts/scan-report.txt @@ -0,0 +1,67 @@ +# 深度扫描报告 + +已收录 parent 数: 61 +扫描页面数: 54 +需补充/遗漏: 10 + +## api/downstreamInterface + parent: Api.DownstreamInterface + inCatalog: true + 页面按钮: + | cancel | ↻ | 保存 | 修改 | 刷新列表 | 刷新接口列表 | 参数配置 | 取消 | 填充到表单 | 操作 | 新增接口 | 新增服务商 | 智能填充 | 调试 | 返回配置 + 目录缺失: + | cancel | ↻ | 操作 + +## api/upstreamInterface + parent: Api.UpstreamInterface + inCatalog: true + 页面按钮: + | AI脚本 | ↻ | 保存 | 删除 | 前置脚本 | 发布 | 取消 | 后置脚本 | 回滚 | 回滚到此版本 | 导入 | 操作 | 新增 | 新增参数 | 新增系统参数 | 格式化 | 温馨提示 | 生成脚本 | 确定 | 解析 | 调试 + 目录缺失: + | ↻ | 操作 | 温馨提示 + +## channel/autoTrigger + parent: Channel.AutoTrigger + inCatalog: true + 页面按钮: 上一页 | 新增 + 目录缺失: 上一页 + +## channel/issueTemplate + parent: Channel.IssueTemplate + inCatalog: true + 页面按钮: 上一页 | 新增 + 目录缺失: 上一页 + +## system/dataPerm/templates + parent: Rbac.DataPerm.Template + inCatalog: true + 页面按钮: 保存 | 写入角色权限 | 删 | 刷新列表 | 套用到用户 | 新建模板 | 普通销售 | 添加明细行 | 添加示例配置 | 请从左侧选择模板,或点击新建 + 目录缺失: 删 | 普通销售 | 请从左侧选择模板,或点击新建 + +## system/dataPerm/users + parent: Rbac.DataPerm + inCatalog: true + 页面按钮: 刷新列表 | 请从左侧选择用户 + 目录缺失: 请从左侧选择用户 + +## system/dict + parent: System.Dict + inCatalog: true + 页面按钮: submit') | 下载 OMS 预置字典 | 下载模板 | 取消 | 批量导入字典 + 目录缺失: submit') + +## system/permission/role + parent: Rbac.Roles + inCatalog: true + 页面按钮: 一级菜单 | 三级按钮 | 二级菜单 | 保存 | 保存权限 | 全选 | 刷新列表 | 取消全选 | 新增角色 | 请从左侧选择角色,或点击新增 + 目录缺失: 一级菜单 | 三级按钮 | 二级菜单 | 请从左侧选择角色,或点击新增 + +## system/xhsAiAssistant + parent: Xhs.Ai + inCatalog: true + 页面按钮: ✎ | 保存 | 刷新 | 取消 | 清空 + 目录缺失: ✎ + +## xhs/skills + parent: Xhs.Skills + inCatalog: true + 页面按钮: okText | ⎘ | ▶ | ✎ | 导入官方示例 | 搭配新技能 | 生成名称 + 目录缺失: okText | ⎘ | ▶ | ✎ + +# 完全未收录的 parentPermissionCode \ No newline at end of file diff --git a/src/api/order/platformStore.ts b/src/api/order/platformStore.ts new file mode 100644 index 0000000..591aa0c --- /dev/null +++ b/src/api/order/platformStore.ts @@ -0,0 +1,47 @@ +import { axiosInstance } from '@/api/rbac' +import { assertBusinessOk, omsUrl, parseListPayload, unwrapData } from '@/api/oms/common' + +function postList(path: string, body: Record) { + return axiosInstance.post(omsUrl(path), body).then((res) => parseListPayload(res.data)) +} + +function postOk(path: string, body: Record) { + return axiosInstance.post(omsUrl(path), body).then((res) => { + assertBusinessOk(res.data) + return unwrapData(res.data) + }) +} + +function getData(path: string, params?: Record) { + return axiosInstance.get(omsUrl(path), { params }).then((res) => unwrapData(res.data)) +} + +// Platform store +export const getPlatformStoreList = (body: Record) => + postList('/order/platform-store/list', body) +export const getPlatformStoreAuthUrl = (body: Record) => + postOk('/order/platform-store/auth-url', body) +export const savePlatformStore = (body: Record) => postOk('/order/platform-store/save', body) +export const deletePlatformStore = (ids: number[]) => postOk('/order/platform-store/delete', { ids }) + +// Platform store order +export const getPlatformStoreOrderList = (body: Record) => + postList('/order/platform-store-order/list', body) +export const getPlatformStoreOrderDetail = (id: number, customerId?: number) => + getData('/order/platform-store-order/detail', { id, customerId }) +export const getPlatformStoreOrderSummary = (params?: Record) => + getData('/order/platform-store-order/summary', params) +export const syncPlatformStoreOrderStatus = (ids: number[], customerId?: number) => + postOk('/order/platform-store-order/sync-status', { ids, customerId }) +export const readyToShipPlatformStoreOrder = (ids: number[], customerId?: number) => + postOk('/order/platform-store-order/ready-to-ship', { ids, customerId }) +export const matchPlatformStoreOrderInventory = (body: Record) => + postOk('/order/platform-store-order/match-inventory', body) +export const batchMatchPlatformStoreOrderInventory = (body: Record) => + postOk('/order/platform-store-order/batch-match-inventory', body) +export const fetchPlatformStoreOrderLabel = (id: number, customerId?: number) => + postOk('/order/platform-store-order/fetch-label', { id, customerId }) +export const togglePlatformStoreOrderSuspend = (body: Record) => + postOk('/order/platform-store-order/toggle-suspend', body) +export const deletePlatformStoreOrder = (ids: number[], customerId?: number) => + postOk('/order/platform-store-order/delete', { ids, customerId }) diff --git a/src/api/warehouse/index.ts b/src/api/warehouse/index.ts new file mode 100644 index 0000000..5ae1206 --- /dev/null +++ b/src/api/warehouse/index.ts @@ -0,0 +1,57 @@ +import { axiosInstance } from '@/api/rbac' +import { assertBusinessOk, omsUrl, parseListPayload, unwrapData } from '@/api/oms/common' + +function postList(path: string, body: Record) { + return axiosInstance.post(omsUrl(path), body).then((res) => parseListPayload(res.data)) +} + +function postOk(path: string, body: Record) { + return axiosInstance.post(omsUrl(path), body).then((res) => { + assertBusinessOk(res.data) + return unwrapData(res.data) + }) +} + +function getData(path: string, params?: Record) { + return axiosInstance.get(omsUrl(path), { params }).then((res) => unwrapData(res.data)) +} + +// SKU +export const getWarehouseSkuList = (body: Record) => postList('/warehouse/sku/list', body) +export const getWarehouseSkuDetail = (id: number, customerId?: number) => + getData('/warehouse/sku/detail', { id, customerId }) +export const saveWarehouseSku = (body: Record) => postOk('/warehouse/sku/save', body) +export const deleteWarehouseSku = (id: number) => postOk('/warehouse/sku/delete', { id }) +export const bindWarehouseSkuMapping = (body: Record) => + postOk('/warehouse/sku/bind-mapping', body) + +// Bin location +export const getWarehouseBinLocationList = (body: Record) => + postList('/warehouse/bin-location/list', body).then((r) => ({ items: r.items, total: r.items.length })) +export const saveWarehouseBinLocation = (body: Record) => + postOk('/warehouse/bin-location/save', body) + +// Inbound +export const getWarehouseInboundList = (body: Record) => postList('/warehouse/inbound/list', body) +export const getWarehouseInboundDetail = (id: number, customerId?: number) => + getData('/warehouse/inbound/detail', { id, customerId }) +export const saveWarehouseInbound = (body: Record) => postOk('/warehouse/inbound/save', body) +export const deleteWarehouseInbound = (id: number) => postOk('/warehouse/inbound/delete', { id }) +export const confirmWarehouseInboundReceive = (body: Record) => + postOk('/warehouse/inbound/confirm-receive', body) +export const getWarehouseInboundSummary = (params?: Record) => + getData('/warehouse/inbound/summary', params) + +// Parcel +export const getWarehouseParcelList = (body: Record) => postList('/warehouse/parcel/list', body) +export const saveWarehouseParcel = (body: Record) => postOk('/warehouse/parcel/save', body) +export const deleteWarehouseParcel = (id: number) => postOk('/warehouse/parcel/delete', { id }) +export const putawayWarehouseParcel = (body: Record) => postOk('/warehouse/parcel/putaway', body) + +// Inventory +export const getWarehouseInventoryList = (body: Record) => + postList('/warehouse/inventory/list', body) +export const getWarehouseInventoryBinDetail = (skuId: number, warehouseId: number, customerId?: number) => + getData('/warehouse/inventory/bin-detail', { skuId, warehouseId, customerId }) +export const relocateWarehouseInventory = (body: Record) => + postOk('/warehouse/inventory/relocate', body) diff --git a/src/components/HandsontablePro/index.vue b/src/components/HandsontablePro/index.vue index b48aeec..764028e 100644 --- a/src/components/HandsontablePro/index.vue +++ b/src/components/HandsontablePro/index.vue @@ -96,6 +96,10 @@ persistColumnOrderKey?: string; // 禁止拖拽的列 key lockedColumnKeys?: string[]; + // 是否启用表头搜索框 + enableHeaderSearch?: boolean; + // 是否启用表头筛选/排序下拉 + enableColumnFilter?: boolean; } const props = withDefaults(defineProps(), { @@ -121,6 +125,8 @@ columnOrder: undefined, persistColumnOrderKey: '', lockedColumnKeys: () => [], + enableHeaderSearch: true, + enableColumnFilter: true, }); // 确保 total 始终是数字类型(用于内部使用) @@ -287,7 +293,7 @@ // 操作列(在前面) if (props.showActionColumn && props.actionColumnPosition === 'start') { - columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htCenter', headerClassName: 'htLeft' }); + columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htLeft', headerClassName: 'htLeft' }); headerTexts.push(props.actionColumnHeader); currentDataIndex++; } @@ -298,7 +304,7 @@ type: 'text', readOnly: true, width: props.enableColumnOrderConfig ? 76 : 60, - className: 'htCenter', + className: 'htLeft', headerClassName: 'htLeft', renderer: ellipsisRenderer }); @@ -310,7 +316,7 @@ effectiveColumns.value.forEach((col, index) => { // beforeLast:在倒数第二列后插入操作列 if (props.showActionColumn && props.actionColumnPosition === 'beforeLast' && index === dataColCount - 1) { - columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htCenter', headerClassName: 'htLeft' }); + columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htLeft', headerClassName: 'htLeft' }); headerTexts.push(props.actionColumnHeader); currentDataIndex++; } @@ -328,7 +334,7 @@ // 操作列(在后面,非 beforeLast 时) if (props.showActionColumn && props.actionColumnPosition === 'end') { - columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htCenter', headerClassName: 'htLeft' }); + columns.push({ data: currentDataIndex, type: 'text', readOnly: true, width: props.actionColumnWidth, className: 'htLeft', headerClassName: 'htLeft' }); headerTexts.push(props.actionColumnHeader); currentDataIndex++; } @@ -424,8 +430,8 @@ horizontal: true, vertical: true }, - filters: { enabled: true }, - dropdownMenu: { + filters: props.enableColumnFilter ? { enabled: true } : false, + dropdownMenu: props.enableColumnFilter ? { items: { sort_asc: { name: '升序排序' }, sort_desc: { name: '降序排序' }, @@ -501,8 +507,8 @@ } }, }, - }, - columnSorting: true, + } : false, + columnSorting: props.enableColumnFilter, beforeColumnMove: (movedColumns: number[]) => { if (!props.enableColumnReorder) return false; // 仅允许移动数据列(复选框/操作/序号列禁止) @@ -561,6 +567,7 @@ const label = col === serialColIndex ? props.serialNoHeader : props.actionColumnHeader; TH.innerHTML = ''; TH.classList.add('ht-header-simple'); + TH.style.textAlign = 'left'; const span = document.createElement('span'); span.className = 'ht-header-simple-text'; span.textContent = label; @@ -609,6 +616,17 @@ const colDef = effectiveColumns.value[dataColIndex]; const searchField = colDef.searchField || props.columnToSearchFieldMap[col]; const headerText = colDef.label; + + if (!props.enableHeaderSearch) { + TH.innerHTML = ''; + TH.classList.add('ht-header-simple'); + TH.style.textAlign = 'left'; + const span = document.createElement('span'); + span.className = 'ht-header-simple-text'; + span.textContent = headerText; + TH.appendChild(span); + return; + } // 检查是否已经创建了搜索框 if (TH.querySelector('.header-search-input')) { @@ -794,7 +812,7 @@ // 操作列(在前面) if (col === actionColStartIndex && row >= 0 && row < props.data.length) { - td.style.textAlign = 'center'; + td.style.textAlign = 'left'; td.style.overflow = 'visible'; const rowData = props.data[row]; if (props.actionRenderer) { @@ -811,7 +829,7 @@ // 序号列 if (col === serialColIndex) { - td.style.textAlign = 'center'; + td.style.textAlign = 'left'; td.innerHTML = value || ''; td.style.color = '#8c8c8c'; td.style.fontWeight = '500'; @@ -820,7 +838,7 @@ // 操作列(在后面) if (col === actionColEndIndex && row >= 0 && row < props.data.length) { - td.style.textAlign = 'center'; + td.style.textAlign = 'left'; td.style.overflow = 'visible'; const rowData = props.data[row]; if (props.actionRenderer) { @@ -1746,6 +1764,7 @@ font-size: 12px; font-weight: 500; color: #1d2129; + text-align: left !important; } } @@ -1764,16 +1783,19 @@ :deep(.ht-header-simple) { padding: 0 !important; vertical-align: middle; + text-align: left !important; } :deep(.ht-header-simple .ht-header-simple-text) { display: block; - text-align: left; + width: 100%; + text-align: left !important; font-size: 12px; font-weight: 500; color: #1d2129; padding: 4px 6px; white-space: nowrap; overflow: visible; + box-sizing: border-box; } :deep(.ht-header-order-config .ht-header-order-config-wrap) { diff --git a/src/components/top-nav/RightTopMessage.vue b/src/components/top-nav/RightTopMessage.vue index 5e5f5fe..79e57c9 100644 --- a/src/components/top-nav/RightTopMessage.vue +++ b/src/components/top-nav/RightTopMessage.vue @@ -65,7 +65,6 @@ const loadNotice = async () => { page: 1, pageSize: 1, noticeType: 'notice', - receiverType: 'user', }); noticeCount.value = total; } catch (error) { @@ -81,7 +80,6 @@ const loadNotification = async () => { page: 1, pageSize: 1, noticeType: 'message', - receiverType: 'user', }); notificationCount.value = total; } catch (error) { diff --git a/src/constants/pageButtonCatalog.ts b/src/constants/pageButtonCatalog.ts index beaa888..fdc57e6 100644 --- a/src/constants/pageButtonCatalog.ts +++ b/src/constants/pageButtonCatalog.ts @@ -481,6 +481,37 @@ const CORE_GROUPS: PageButtonGroup[] = [ { code: 'Retry', name: '重试失败' }, { code: 'Cancel', name: '取消待处理' }, ]), + B('Order.PlatformStore', [ + { code: 'Query', name: '查询' }, + { code: 'Save', name: '保存' }, + { code: 'Delete', name: '删除' }, + { code: 'Auth', name: '授权' }, + ]), + B('Order.PlatformStoreOrder', [ + { code: 'Query', name: '查询' }, + { code: 'MatchInventory', name: '匹配库存' }, + { code: 'ToggleSuspend', name: '搁置/恢复' }, + { code: 'Delete', name: '删除' }, + ]), + B('Warehouse.Sku', [ + { code: 'Query', name: '查询' }, + { code: 'Save', name: '保存' }, + { code: 'Delete', name: '删除' }, + ]), + B('Warehouse.Inventory', [ + { code: 'Query', name: '查询' }, + { code: 'Relocate', name: '换库位' }, + ]), + B('Warehouse.Parcel', [ + { code: 'Query', name: '查询' }, + { code: 'Save', name: '保存' }, + { code: 'Delete', name: '删除' }, + ]), + B('Warehouse.InboundNotice', [ + { code: 'Query', name: '查询' }, + { code: 'Save', name: '保存' }, + { code: 'Delete', name: '删除' }, + ]), // ── 渠道 ── B('Channel.SalesProducts', [ diff --git a/src/locale/en-US.ts b/src/locale/en-US.ts index 76950a7..6d2c3e6 100644 --- a/src/locale/en-US.ts +++ b/src/locale/en-US.ts @@ -83,6 +83,167 @@ export default { 'menu.order.templateMapping': 'Template Mapping', 'menu.order.myOrders': 'My Orders', 'menu.order.batchJobs': 'Batch Jobs', + 'menu.order.platformStore': 'Platform Stores', + 'menu.order.platformStoreOrder': 'Store Orders', + 'menu.warehouse': 'Warehouse', + 'menu.warehouse.parcel': 'My Parcels', + 'menu.warehouse.inventory': 'My Inventory', + 'menu.warehouse.sku': 'My SKU', + 'menu.warehouse.inboundNotice': 'Inbound Notice', + 'warehouse.common.search': 'Search', + 'warehouse.common.add': 'Add', + 'warehouse.common.edit': 'Edit', + 'warehouse.common.delete': 'Delete', + 'warehouse.common.save': 'Save', + 'warehouse.common.cancel': 'Cancel', + 'warehouse.common.confirm': 'Confirm', + 'warehouse.common.detail': 'Detail', + 'warehouse.common.warehouse': 'Warehouse', + 'warehouse.sku.table.skuCode': 'SKU Code', + 'warehouse.sku.table.skuName': 'SKU Name', + 'warehouse.sku.table.totalQty': 'Qty', + 'warehouse.sku.table.weightG': 'Weight(g)', + 'warehouse.sku.table.remark': 'Remark', + 'warehouse.sku.search.keyword': 'Code / Name', + 'warehouse.sku.form.skuCode': 'SKU Code', + 'warehouse.sku.form.skuName': 'SKU Name', + 'warehouse.sku.form.weightG': 'Weight(g)', + 'warehouse.sku.form.remark': 'Remark', + 'warehouse.sku.modal.add': 'Add SKU', + 'warehouse.sku.modal.edit': 'Edit SKU', + 'warehouse.sku.actions.delete': 'Delete SKU', + 'warehouse.sku.message.loadFailed': 'Failed to load SKU list', + 'warehouse.sku.message.saveSuccess': 'Saved', + 'warehouse.sku.message.saveFailed': 'Save failed', + 'warehouse.sku.message.deleteSuccess': 'Deleted', + 'warehouse.sku.message.deleteFailed': 'Delete failed', + 'warehouse.sku.message.deleteConfirm': 'Delete {code}?', + 'warehouse.sku.message.required': 'SKU code and name are required', + 'warehouse.inventory.table.skuCode': 'SKU Code', + 'warehouse.inventory.table.skuName': 'SKU Name', + 'warehouse.inventory.table.warehouseId': 'Warehouse', + 'warehouse.inventory.table.totalQty': 'Total Qty', + 'warehouse.inventory.table.binCount': 'Bins', + 'warehouse.inventory.table.binCode': 'Bin', + 'warehouse.inventory.table.qty': 'Qty', + 'warehouse.inventory.search.keyword': 'Code / Name', + 'warehouse.inventory.actions.binDetail': 'Bin Detail', + 'warehouse.inventory.actions.relocate': 'Relocate', + 'warehouse.inventory.drawer.binDetail': 'Bin Detail', + 'warehouse.inventory.modal.relocate': 'Relocate', + 'warehouse.inventory.form.sourceBin': 'Source Bin ID', + 'warehouse.inventory.form.targetBin': 'Target Bin ID', + 'warehouse.inventory.form.qty': 'Qty', + 'warehouse.inventory.message.loadFailed': 'Failed to load inventory', + 'warehouse.inventory.message.binDetailFailed': 'Failed to load bin detail', + 'warehouse.inventory.message.relocateRequired': 'Fill relocate fields', + 'warehouse.inventory.message.relocateSuccess': 'Relocated', + 'warehouse.inventory.message.relocateFailed': 'Relocate failed', + 'warehouse.parcel.status.all': 'All', + 'warehouse.parcel.status.inTransit': 'In Transit', + 'warehouse.parcel.status.arrived': 'Arrived', + 'warehouse.parcel.status.stored': 'Stored', + 'warehouse.parcel.table.trackingNo': 'Tracking No', + 'warehouse.parcel.table.carrierName': 'Carrier', + 'warehouse.parcel.table.lifecycleStatus': 'Status', + 'warehouse.parcel.table.warehouseId': 'Warehouse', + 'warehouse.parcel.table.remark': 'Remark', + 'warehouse.parcel.search.trackingNo': 'Tracking No', + 'warehouse.parcel.form.trackingNo': 'Tracking No', + 'warehouse.parcel.form.carrierName': 'Carrier', + 'warehouse.parcel.form.productName': 'Product', + 'warehouse.parcel.form.quantity': 'Qty', + 'warehouse.parcel.modal.add': 'Add Parcel', + 'warehouse.parcel.actions.delete': 'Delete Parcel', + 'warehouse.parcel.message.loadFailed': 'Failed to load parcels', + 'warehouse.parcel.message.saveSuccess': 'Saved', + 'warehouse.parcel.message.saveFailed': 'Save failed', + 'warehouse.parcel.message.deleteSuccess': 'Deleted', + 'warehouse.parcel.message.required': 'Warehouse and tracking no required', + 'warehouse.inbound.status.all': 'All', + 'warehouse.inbound.status.forecasted': 'Forecasted', + 'warehouse.inbound.status.completed': 'Completed', + 'warehouse.inbound.table.noticeNo': 'Notice No', + 'warehouse.inbound.table.markReference': 'Mark Ref', + 'warehouse.inbound.table.receiptStatus': 'Status', + 'warehouse.inbound.table.boxCount': 'Boxes', + 'warehouse.inbound.table.plannedQty': 'Planned Qty', + 'warehouse.inbound.table.createTime': 'Created', + 'warehouse.inbound.search.keyword': 'Notice / Mark', + 'warehouse.inbound.form.markReference': 'Mark Ref', + 'warehouse.inbound.form.markBoxNo': 'Box No', + 'warehouse.inbound.form.sku': 'SKU', + 'warehouse.inbound.form.plannedQty': 'Planned Qty', + 'warehouse.inbound.modal.add': 'Add Inbound', + 'warehouse.inbound.drawer.detail': 'Inbound Detail', + 'warehouse.inbound.box': 'Box', + 'warehouse.inbound.line.skuCode': 'SKU', + 'warehouse.inbound.line.plannedQty': 'Planned', + 'warehouse.inbound.line.receivedQty': 'Received', + 'warehouse.inbound.actions.delete': 'Delete', + 'warehouse.inbound.message.loadFailed': 'Failed to load inbound list', + 'warehouse.inbound.message.saveSuccess': 'Saved', + 'warehouse.inbound.message.saveFailed': 'Save failed', + 'warehouse.inbound.message.deleteSuccess': 'Deleted', + 'warehouse.inbound.message.required': 'Select warehouse and SKU', + 'warehouse.inbound.message.detailFailed': 'Failed to load detail', + 'order.platformStore.platform.manual': 'Manual', + 'order.platformStore.table.platform': 'Platform', + 'order.platformStore.table.nickname': 'Nickname', + 'order.platformStore.table.account': 'Account', + 'order.platformStore.table.authStatus': 'Auth Status', + 'order.platformStore.table.tokenExpire': 'Token Expire', + 'order.platformStore.search.platform': 'Platform', + 'order.platformStore.search.nickname': 'Nickname', + 'order.platformStore.form.platform': 'Platform', + 'order.platformStore.form.nickname': 'Nickname', + 'order.platformStore.form.account': 'Account', + 'order.platformStore.form.autoFulfill': 'Auto Fulfill', + 'order.platformStore.modal.add': 'Add Store', + 'order.platformStore.modal.edit': 'Edit Store', + 'order.platformStore.actions.auth': 'Authorize', + 'order.platformStore.actions.delete': 'Delete Store', + 'order.platformStore.message.loadFailed': 'Failed to load stores', + 'order.platformStore.message.saveSuccess': 'Saved', + 'order.platformStore.message.saveFailed': 'Save failed', + 'order.platformStore.message.deleteSuccess': 'Deleted', + 'order.platformStore.message.required': 'Nickname is required', + 'order.platformStore.message.authPlaceholder': 'OAuth placeholder', + 'order.platformStore.message.authFailed': 'Failed to get auth URL', + 'order.platformStoreOrder.status.all': 'All', + 'order.platformStoreOrder.status.pending': 'Pending', + 'order.platformStoreOrder.status.toShip': 'To Ship', + 'order.platformStoreOrder.status.shipped': 'Shipped', + 'order.platformStoreOrder.table.orderNo': 'Order No', + 'order.platformStoreOrder.table.store': 'Store', + 'order.platformStoreOrder.table.status': 'Status', + 'order.platformStoreOrder.table.amount': 'Amount', + 'order.platformStoreOrder.table.orderTime': 'Order Time', + 'order.platformStoreOrder.table.linkedServiceNo': 'Linked Service No', + 'order.platformStoreOrder.form.product': 'Sales Product', + 'order.platformStoreOrder.search.orderNo': 'Order No', + 'order.platformStoreOrder.summary.pending': 'Pending', + 'order.platformStoreOrder.summary.toShip': 'To Ship', + 'order.platformStoreOrder.drawer.detail': 'Order Detail', + 'order.platformStoreOrder.line.sku': 'Platform SKU', + 'order.platformStoreOrder.line.name': 'Product', + 'order.platformStoreOrder.line.qty': 'Qty', + 'order.platformStoreOrder.line.mappedSku': 'Mapped SKU', + 'order.platformStoreOrder.actions.match': 'Match Inventory', + 'order.platformStoreOrder.actions.batchMatch': 'Batch Match', + 'order.platformStoreOrder.actions.suspend': 'Suspend', + 'order.platformStoreOrder.actions.resume': 'Resume', + 'order.platformStoreOrder.actions.delete': 'Delete', + 'order.platformStoreOrder.message.loadFailed': 'Failed to load orders', + 'order.platformStoreOrder.message.detailFailed': 'Failed to load detail', + 'order.platformStoreOrder.message.matchSuccess': 'Inventory matched', + 'order.platformStoreOrder.message.matchFailed': 'Match failed', + 'order.platformStoreOrder.message.warehouseRequired': 'Select warehouse', + 'order.platformStoreOrder.message.suspendSuccess': 'Status updated', + 'order.platformStoreOrder.message.deleteSuccess': 'Deleted', + 'order.platformStoreOrder.message.batchEmpty': 'No pending orders to match on this page', + 'order.platformStoreOrder.message.batchConfirm': 'Match {count} pending orders on this page and create parcel orders?', + 'order.platformStoreOrder.message.batchResult': 'Batch done: {success} succeeded, {fail} failed', 'menu.channel': 'Channel', 'menu.channel.channelGuide': 'Getting Started', 'menu.channel.salesProducts': 'Sales Products', @@ -1148,6 +1309,7 @@ export default { 'system.menu.actions.more': 'More', 'system.menu.actions.manageButton': 'Manage button', 'system.menu.actions.syncLevel3Buttons': 'Sync level-3 buttons', + 'system.menu.actions.syncSubMenusAndButtons': 'Sync sub-menus & buttons', 'system.menu.status.enabled': 'Enabled', 'system.menu.status.disabled': 'Disabled', 'system.menu.table.title': 'Menu name', @@ -1171,10 +1333,18 @@ export default { 'system.menu.modal.okImport': 'Confirm import', 'system.menu.modal.syncLevel3Title': 'Sync level-3 buttons', 'system.menu.modal.syncLevel3Content': 'Sync level-3 buttons from the frontend catalog and permission tree for menu "{name}". Existing buttons will be skipped.', + 'system.menu.modal.syncModuleTitle': 'Sync sub-menus & buttons', + 'system.menu.modal.syncModuleContent': + 'Sync level-2 page menus from route config for module "{name}", then sync level-3 buttons for each page. Existing menus/buttons will be skipped.', 'system.menu.modal.syncLevel3Ok': 'Sync now', 'system.menu.message.syncLevel3Success': 'Synced: {created} created, {skipped} skipped', 'system.menu.message.syncLevel3Skipped': 'Nothing to sync, {skipped} existing button(s) skipped', 'system.menu.message.syncLevel3Failed': 'Failed to sync level-3 buttons', + 'system.menu.message.syncModuleSuccess': + 'Synced: {level2Created} level-2 menu(s) created, {level2Skipped} skipped; {level3Created} level-3 button(s) created, {level3Skipped} skipped', + 'system.menu.message.syncModuleSkipped': + 'Nothing to sync, skipped {level2Skipped} level-2 menu(s) and {level3Skipped} level-3 button(s)', + 'system.menu.message.syncModulePartialFailed': 'Some pages failed to sync level-3 buttons: {details}', // System - Organization Management 'system.organization.actions.add': 'Add Organization', diff --git a/src/locale/zh-CN.ts b/src/locale/zh-CN.ts index e0edc1c..a9f3ea9 100644 --- a/src/locale/zh-CN.ts +++ b/src/locale/zh-CN.ts @@ -83,6 +83,167 @@ export default { 'menu.order.templateMapping': '模板字段映射', 'menu.order.myOrders': '我的订单', 'menu.order.batchJobs': '批量任务', + 'menu.order.platformStore': '店铺授权', + 'menu.order.platformStoreOrder': '店铺订单', + 'menu.warehouse': '仓储', + 'menu.warehouse.parcel': '我的包裹', + 'menu.warehouse.inventory': '我的库存', + 'menu.warehouse.sku': '我的 SKU', + 'menu.warehouse.inboundNotice': '入库预报', + 'warehouse.common.search': '查询', + 'warehouse.common.add': '新增', + 'warehouse.common.edit': '编辑', + 'warehouse.common.delete': '删除', + 'warehouse.common.save': '保存', + 'warehouse.common.cancel': '取消', + 'warehouse.common.confirm': '确定', + 'warehouse.common.detail': '详情', + 'warehouse.common.warehouse': '仓库', + 'warehouse.sku.table.skuCode': 'SKU 编码', + 'warehouse.sku.table.skuName': 'SKU 名称', + 'warehouse.sku.table.totalQty': '库存', + 'warehouse.sku.table.weightG': '重量(g)', + 'warehouse.sku.table.remark': '备注', + 'warehouse.sku.search.keyword': '编码/名称', + 'warehouse.sku.form.skuCode': 'SKU 编码', + 'warehouse.sku.form.skuName': 'SKU 名称', + 'warehouse.sku.form.weightG': '重量(g)', + 'warehouse.sku.form.remark': '备注', + 'warehouse.sku.modal.add': '新增 SKU', + 'warehouse.sku.modal.edit': '编辑 SKU', + 'warehouse.sku.actions.delete': '删除 SKU', + 'warehouse.sku.message.loadFailed': '加载 SKU 列表失败', + 'warehouse.sku.message.saveSuccess': '保存成功', + 'warehouse.sku.message.saveFailed': '保存失败', + 'warehouse.sku.message.deleteSuccess': '删除成功', + 'warehouse.sku.message.deleteFailed': '删除失败', + 'warehouse.sku.message.deleteConfirm': '确定删除 {code}?', + 'warehouse.sku.message.required': '请填写 SKU 编码和名称', + 'warehouse.inventory.table.skuCode': 'SKU 编码', + 'warehouse.inventory.table.skuName': 'SKU 名称', + 'warehouse.inventory.table.warehouseId': '仓库', + 'warehouse.inventory.table.totalQty': '总数量', + 'warehouse.inventory.table.binCount': '库位数', + 'warehouse.inventory.table.binCode': '库位', + 'warehouse.inventory.table.qty': '数量', + 'warehouse.inventory.search.keyword': '编码/名称', + 'warehouse.inventory.actions.binDetail': '库位明细', + 'warehouse.inventory.actions.relocate': '换库位', + 'warehouse.inventory.drawer.binDetail': '库位明细', + 'warehouse.inventory.modal.relocate': '换库位', + 'warehouse.inventory.form.sourceBin': '源库位 ID', + 'warehouse.inventory.form.targetBin': '目标库位 ID', + 'warehouse.inventory.form.qty': '数量', + 'warehouse.inventory.message.loadFailed': '加载库存失败', + 'warehouse.inventory.message.binDetailFailed': '加载库位明细失败', + 'warehouse.inventory.message.relocateRequired': '请填写换库位信息', + 'warehouse.inventory.message.relocateSuccess': '换库位成功', + 'warehouse.inventory.message.relocateFailed': '换库位失败', + 'warehouse.parcel.status.all': '全部', + 'warehouse.parcel.status.inTransit': '在途', + 'warehouse.parcel.status.arrived': '已到仓', + 'warehouse.parcel.status.stored': '已上架', + 'warehouse.parcel.table.trackingNo': '快递单号', + 'warehouse.parcel.table.carrierName': '快递公司', + 'warehouse.parcel.table.lifecycleStatus': '状态', + 'warehouse.parcel.table.warehouseId': '仓库', + 'warehouse.parcel.table.remark': '备注', + 'warehouse.parcel.search.trackingNo': '快递单号', + 'warehouse.parcel.form.trackingNo': '快递单号', + 'warehouse.parcel.form.carrierName': '快递公司', + 'warehouse.parcel.form.productName': '商品名称', + 'warehouse.parcel.form.quantity': '数量', + 'warehouse.parcel.modal.add': '新增包裹', + 'warehouse.parcel.actions.delete': '删除包裹', + 'warehouse.parcel.message.loadFailed': '加载包裹失败', + 'warehouse.parcel.message.saveSuccess': '保存成功', + 'warehouse.parcel.message.saveFailed': '保存失败', + 'warehouse.parcel.message.deleteSuccess': '删除成功', + 'warehouse.parcel.message.required': '请填写仓库和快递单号', + 'warehouse.inbound.status.all': '全部', + 'warehouse.inbound.status.forecasted': '预报', + 'warehouse.inbound.status.completed': '已完成', + 'warehouse.inbound.table.noticeNo': '预报单号', + 'warehouse.inbound.table.markReference': '唛头', + 'warehouse.inbound.table.receiptStatus': '状态', + 'warehouse.inbound.table.boxCount': '箱数', + 'warehouse.inbound.table.plannedQty': '计划数量', + 'warehouse.inbound.table.createTime': '创建时间', + 'warehouse.inbound.search.keyword': '单号/唛头', + 'warehouse.inbound.form.markReference': '唛头', + 'warehouse.inbound.form.markBoxNo': '箱号', + 'warehouse.inbound.form.sku': 'SKU', + 'warehouse.inbound.form.plannedQty': '计划数量', + 'warehouse.inbound.modal.add': '新增入库预报', + 'warehouse.inbound.drawer.detail': '入库详情', + 'warehouse.inbound.box': '箱', + 'warehouse.inbound.line.skuCode': 'SKU', + 'warehouse.inbound.line.plannedQty': '计划', + 'warehouse.inbound.line.receivedQty': '实收', + 'warehouse.inbound.actions.delete': '删除预报', + 'warehouse.inbound.message.loadFailed': '加载入库预报失败', + 'warehouse.inbound.message.saveSuccess': '保存成功', + 'warehouse.inbound.message.saveFailed': '保存失败', + 'warehouse.inbound.message.deleteSuccess': '删除成功', + 'warehouse.inbound.message.required': '请选择仓库和 SKU', + 'warehouse.inbound.message.detailFailed': '加载详情失败', + 'order.platformStore.platform.manual': '手工店铺', + 'order.platformStore.table.platform': '平台', + 'order.platformStore.table.nickname': '店铺昵称', + 'order.platformStore.table.account': '账号', + 'order.platformStore.table.authStatus': '授权状态', + 'order.platformStore.table.tokenExpire': 'Token 过期', + 'order.platformStore.search.platform': '平台', + 'order.platformStore.search.nickname': '店铺昵称', + 'order.platformStore.form.platform': '平台', + 'order.platformStore.form.nickname': '店铺昵称', + 'order.platformStore.form.account': '平台账号', + 'order.platformStore.form.autoFulfill': '自动发货', + 'order.platformStore.modal.add': '新增店铺', + 'order.platformStore.modal.edit': '编辑店铺', + 'order.platformStore.actions.auth': '授权', + 'order.platformStore.actions.delete': '删除店铺', + 'order.platformStore.message.loadFailed': '加载店铺失败', + 'order.platformStore.message.saveSuccess': '保存成功', + 'order.platformStore.message.saveFailed': '保存失败', + 'order.platformStore.message.deleteSuccess': '删除成功', + 'order.platformStore.message.required': '请填写店铺昵称', + 'order.platformStore.message.authPlaceholder': 'OAuth 占位,待平台 SDK 接入', + 'order.platformStore.message.authFailed': '获取授权地址失败', + 'order.platformStoreOrder.status.all': '全部', + 'order.platformStoreOrder.status.pending': '待处理', + 'order.platformStoreOrder.status.toShip': '待发货', + 'order.platformStoreOrder.status.shipped': '已发货', + 'order.platformStoreOrder.table.orderNo': '平台订单号', + 'order.platformStoreOrder.table.store': '店铺', + 'order.platformStoreOrder.table.status': '状态', + 'order.platformStoreOrder.table.amount': '金额', + 'order.platformStoreOrder.table.orderTime': '下单时间', + 'order.platformStoreOrder.table.linkedServiceNo': '关联服务单号', + 'order.platformStoreOrder.form.product': '销售产品', + 'order.platformStoreOrder.search.orderNo': '平台订单号', + 'order.platformStoreOrder.summary.pending': '待处理', + 'order.platformStoreOrder.summary.toShip': '待发货', + 'order.platformStoreOrder.drawer.detail': '订单详情', + 'order.platformStoreOrder.line.sku': '平台 SKU', + 'order.platformStoreOrder.line.name': '商品', + 'order.platformStoreOrder.line.qty': '数量', + 'order.platformStoreOrder.line.mappedSku': '库内 SKU', + 'order.platformStoreOrder.actions.match': '匹配库存', + 'order.platformStoreOrder.actions.batchMatch': '批量匹配', + 'order.platformStoreOrder.actions.suspend': '搁置', + 'order.platformStoreOrder.actions.resume': '恢复', + 'order.platformStoreOrder.actions.delete': '删除订单', + 'order.platformStoreOrder.message.loadFailed': '加载订单失败', + 'order.platformStoreOrder.message.detailFailed': '加载详情失败', + 'order.platformStoreOrder.message.matchSuccess': '库存匹配成功', + 'order.platformStoreOrder.message.matchFailed': '库存匹配失败', + 'order.platformStoreOrder.message.warehouseRequired': '请选择发货仓库', + 'order.platformStoreOrder.message.suspendSuccess': '状态已更新', + 'order.platformStoreOrder.message.deleteSuccess': '删除成功', + 'order.platformStoreOrder.message.batchEmpty': '当前页没有可匹配的待处理订单', + 'order.platformStoreOrder.message.batchConfirm': '将匹配当前页 {count} 个待处理订单并创建小包单,是否继续?', + 'order.platformStoreOrder.message.batchResult': '批量匹配完成:成功 {success},失败 {fail}', 'menu.channel': '渠道', 'menu.channel.channelGuide': '新手指引', 'menu.channel.salesProducts': '销售产品', @@ -1033,6 +1194,7 @@ export default { 'system.menu.actions.more': '更多', 'system.menu.actions.manageButton': '管理按钮', 'system.menu.actions.syncLevel3Buttons': '同步三级按钮', + 'system.menu.actions.syncSubMenusAndButtons': '同步子菜单及按钮', 'system.menu.status.enabled': '启用', 'system.menu.status.disabled': '禁用', 'system.menu.table.title': '菜单名称', @@ -1056,10 +1218,18 @@ export default { 'system.menu.modal.okImport': '确定导入', 'system.menu.modal.syncLevel3Title': '同步三级按钮', 'system.menu.modal.syncLevel3Content': '将为菜单「{name}」同步前端目录与权限树中的三级按钮,已存在的按钮将跳过。', + 'system.menu.modal.syncModuleTitle': '同步子菜单及按钮', + 'system.menu.modal.syncModuleContent': + '将为模块「{name}」从路由配置同步二级页面菜单,并为每个页面同步三级按钮,已存在的菜单/按钮将跳过。', 'system.menu.modal.syncLevel3Ok': '开始同步', 'system.menu.message.syncLevel3Success': '同步完成:新增 {created} 个,跳过 {skipped} 个', 'system.menu.message.syncLevel3Skipped': '无需同步,已跳过 {skipped} 个已存在按钮', 'system.menu.message.syncLevel3Failed': '同步三级按钮失败', + 'system.menu.message.syncModuleSuccess': + '同步完成:二级菜单新增 {level2Created} 个、跳过 {level2Skipped} 个;三级按钮新增 {level3Created} 个、跳过 {level3Skipped} 个', + 'system.menu.message.syncModuleSkipped': + '无需同步,已跳过 {level2Skipped} 个二级菜单、{level3Skipped} 个三级按钮', + 'system.menu.message.syncModulePartialFailed': '部分页面三级按钮同步失败:{details}', // 系统 - 组织管理 'system.organization.actions.add': '新增组织', diff --git a/src/router/routes/newModules/order.ts b/src/router/routes/newModules/order.ts index 4f7fc6e..a967d27 100644 --- a/src/router/routes/newModules/order.ts +++ b/src/router/routes/newModules/order.ts @@ -70,6 +70,26 @@ const ORDER: AppRouteRecordRaw = { permission: 'Order.BatchJobs.Query', }, }, + { + path: 'platformStore', + name: 'PlatformStore', + component: () => import('@/views/order/platformStore/index.vue'), + meta: { + locale: 'menu.order.platformStore', + requiresAuth: true, + permission: 'Order.PlatformStore.Query', + }, + }, + { + path: 'platformStoreOrder', + name: 'PlatformStoreOrder', + component: () => import('@/views/order/platformStoreOrder/index.vue'), + meta: { + locale: 'menu.order.platformStoreOrder', + requiresAuth: true, + permission: 'Order.PlatformStoreOrder.Query', + }, + }, ], }; diff --git a/src/router/routes/newModules/warehouse.ts b/src/router/routes/newModules/warehouse.ts new file mode 100644 index 0000000..5890ac5 --- /dev/null +++ b/src/router/routes/newModules/warehouse.ts @@ -0,0 +1,58 @@ +import { DEFAULT_LAYOUT } from '../base'; +import { AppRouteRecordRaw } from '../types'; + +const WAREHOUSE: AppRouteRecordRaw = { + path: '/warehouse', + name: 'Warehouse', + component: DEFAULT_LAYOUT, + meta: { + locale: 'menu.warehouse', + icon: 'icon-storage', + requiresAuth: true, + order: 4, + }, + children: [ + { + path: 'parcel', + name: 'WarehouseParcel', + component: () => import('@/views/warehouse/parcel/index.vue'), + meta: { + locale: 'menu.warehouse.parcel', + requiresAuth: true, + permission: 'Warehouse.Parcel.Query', + }, + }, + { + path: 'inventory', + name: 'WarehouseInventory', + component: () => import('@/views/warehouse/inventory/index.vue'), + meta: { + locale: 'menu.warehouse.inventory', + requiresAuth: true, + permission: 'Warehouse.Inventory.Query', + }, + }, + { + path: 'sku', + name: 'WarehouseSku', + component: () => import('@/views/warehouse/sku/index.vue'), + meta: { + locale: 'menu.warehouse.sku', + requiresAuth: true, + permission: 'Warehouse.Sku.Query', + }, + }, + { + path: 'inboundNotice', + name: 'WarehouseInboundNotice', + component: () => import('@/views/warehouse/inboundNotice/index.vue'), + meta: { + locale: 'menu.warehouse.inboundNotice', + requiresAuth: true, + permission: 'Warehouse.InboundNotice.Query', + }, + }, + ], +}; + +export default WAREHOUSE; diff --git a/src/utils/syncMenuLevel3Buttons.ts b/src/utils/syncMenuLevel3Buttons.ts index 1dcd25d..85732b7 100644 --- a/src/utils/syncMenuLevel3Buttons.ts +++ b/src/utils/syncMenuLevel3Buttons.ts @@ -6,6 +6,13 @@ import { normalizeResourcePermissionCode, type PageButtonDef, } from '@/constants/pageButtonCatalog'; +import { + findModuleRouteByMenu, + findPageChildMenu, + getPageRoutesFromModule, + isModuleMenu, + type RoutePageMenuDef, +} from '@/utils/syncMenuRouteCatalog'; export interface SyncLevel3ButtonsResult { created: number; @@ -14,6 +21,22 @@ export interface SyncLevel3ButtonsResult { createdNames: string[]; } +export interface SyncLevel3Options { + /** 无三级按钮时不抛错,返回 created=0 */ + allowEmpty?: boolean; +} + +export interface SyncMenuTreeResult { + mode: 'module' | 'page'; + level2Created: number; + level2Skipped: number; + level3Created: number; + level3Skipped: number; + level3FailedPages: string[]; +} + +export { isModuleMenu }; + function permissionNodeToButton( child: PermissionDefinitionDto, order: number, @@ -137,10 +160,70 @@ function filterSyncTargets( return buttons.filter((btn) => btn.permissionCode !== menuCode); } +function findMenuById(tree: MenuTreeDto[], id: string): MenuTreeDto | null { + for (const node of tree) { + if (node.id === id) return node; + if (node.children?.length) { + const found = findMenuById(node.children, id); + if (found) return found; + } + } + return null; +} + +async function reloadMenuNode(menuId: string): Promise { + const tree = await MenuService.getRbacMenuGetMenuTree(); + return findMenuById(tree ?? [], menuId); +} + +async function ensurePageMenu( + parentMenu: MenuTreeDto, + pageDef: RoutePageMenuDef, +): Promise<{ menu: MenuTreeDto; created: boolean }> { + const existing = findPageChildMenu(parentMenu, pageDef.route, pageDef.permissionCode); + if (existing?.id) { + return { menu: existing, created: false }; + } + + const createdMenu = await MenuService.postRbacMenuCreate({ + pId: parentMenu.id, + name: pageDef.name, + type: 1, + permissionCode: pageDef.permissionCode, + icon: pageDef.icon, + route: pageDef.route, + component: pageDef.component, + order: pageDef.order, + isHidden: pageDef.isHidden, + isCached: false, + description: `同步二级菜单: ${pageDef.route}`, + }); + + return { + menu: { + id: createdMenu.id, + pId: parentMenu.id, + name: pageDef.name, + type: 1, + permissionCode: pageDef.permissionCode, + icon: pageDef.icon, + route: pageDef.route, + component: pageDef.component, + order: pageDef.order, + isHidden: pageDef.isHidden, + children: [], + }, + created: true, + }; +} + /** * 将前端目录 + 权限树中的三级按钮同步为菜单子节点(type=2) */ -export async function syncMenuLevel3Buttons(menu: MenuTreeDto): Promise { +export async function syncMenuLevel3Buttons( + menu: MenuTreeDto, + options?: SyncLevel3Options, +): Promise { const parentPermissionCode = menu.permissionCode?.trim() || ''; if (!parentPermissionCode) { throw new Error('当前菜单未配置权限编码,无法同步三级按钮'); @@ -167,6 +250,9 @@ export async function syncMenuLevel3Buttons(menu: MenuTreeDto): Promise { + if (!menu.id) { + throw new Error('菜单 ID 无效'); + } + if (menu.type !== 1) { + throw new Error('仅支持对菜单类型节点执行同步'); + } + + if (!isModuleMenu(menu)) { + const result = await syncMenuLevel3Buttons(menu); + return { + mode: 'page', + level2Created: 0, + level2Skipped: 0, + level3Created: result.created, + level3Skipped: result.skipped, + level3FailedPages: [], + }; + } + + const moduleRoute = findModuleRouteByMenu(menu); + if (!moduleRoute) { + throw new Error('未找到匹配的路由模块,请确认菜单路由路径与前端路由配置一致'); + } + + const pageDefs = getPageRoutesFromModule(moduleRoute); + if (!pageDefs.length) { + throw new Error('路由模块下没有可同步的二级页面菜单'); + } + + let level2Created = 0; + let level2Skipped = 0; + let level3Created = 0; + let level3Skipped = 0; + const level3FailedPages: string[] = []; + + let currentParent = menu; + + for (const pageDef of pageDefs) { + const { menu: pageMenu, created } = await ensurePageMenu(currentParent, pageDef); + if (created) { + level2Created += 1; + const refreshedParent = await reloadMenuNode(menu.id); + if (refreshedParent) { + currentParent = refreshedParent; + } + } else { + level2Skipped += 1; + } + + if (!pageMenu.permissionCode?.trim()) { + continue; + } + + const pageNode = + findPageChildMenu(currentParent, pageDef.route, pageDef.permissionCode) || pageMenu; + const freshPage = pageNode.id ? await reloadMenuNode(pageNode.id) : null; + const targetPage = freshPage || pageNode; + + try { + const btnResult = await syncMenuLevel3Buttons(targetPage, { allowEmpty: true }); + level3Created += btnResult.created; + level3Skipped += btnResult.skipped; + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error); + level3FailedPages.push(`${pageDef.name}: ${message}`); + } + } + + return { + mode: 'module', + level2Created, + level2Skipped, + level3Created, + level3Skipped, + level3FailedPages, + }; +} diff --git a/src/utils/syncMenuRouteCatalog.ts b/src/utils/syncMenuRouteCatalog.ts new file mode 100644 index 0000000..902d61c --- /dev/null +++ b/src/utils/syncMenuRouteCatalog.ts @@ -0,0 +1,128 @@ +import i18n from '@/locale'; +import { appRoutes } from '@/router/routes'; +import type { AppRouteRecordRaw } from '@/router/routes/types'; +import type { MenuTreeDto } from '@/api/rbac'; + +export interface RoutePageMenuDef { + name: string; + route: string; + component?: string; + permissionCode?: string; + icon?: string; + order: number; + isHidden: boolean; +} + +function normalizeRoutePath(path: string): string { + const trimmed = path.trim().replace(/\/+$/, ''); + return trimmed || '/'; +} + +function joinRoutePath(parentPath: string, childPath: string): string { + if (childPath.startsWith('/')) return normalizeRoutePath(childPath); + const base = normalizeRoutePath(parentPath); + return normalizeRoutePath(`${base}/${childPath}`); +} + +export function extractComponentPath(component: unknown): string | undefined { + if (typeof component === 'string') { + return component; + } + if (typeof component === 'function') { + try { + const componentStr = component.toString(); + const match = componentStr.match(/import\(['"]@\/views\/([^'"]+)\.vue['"]\)/); + if (match?.[1]) { + return `views/${match[1]}`; + } + } catch { + // ignore + } + } + return undefined; +} + +export function resolveRouteMenuTitle(route: AppRouteRecordRaw): string { + const localeKey = route.meta?.locale as string | undefined; + if (localeKey) { + const title = i18n.global.t(localeKey); + if (title && title !== localeKey) return title; + } + return String(route.name || route.path); +} + +function toRouteRecord(route: AppRouteRecordRaw): AppRouteRecordRaw { + return route; +} + +export function findModuleRouteByMenu(menu: MenuTreeDto): AppRouteRecordRaw | undefined { + const menuRoute = normalizeRoutePath(menu.route || ''); + if (menuRoute && menuRoute !== '/') { + for (const route of appRoutes as AppRouteRecordRaw[]) { + if (normalizeRoutePath(route.path) === menuRoute) { + return toRouteRecord(route); + } + } + } + + const permissionPrefix = menu.permissionCode?.trim(); + if (permissionPrefix) { + for (const route of appRoutes as AppRouteRecordRaw[]) { + const children = route.children || []; + const matched = children.some((child) => { + const code = (child.meta?.permission as string | undefined)?.trim(); + return code?.startsWith(`${permissionPrefix}.`); + }); + if (matched) return toRouteRecord(route); + } + } + + return undefined; +} + +export function getPageRoutesFromModule(moduleRoute: AppRouteRecordRaw): RoutePageMenuDef[] { + const parentPath = normalizeRoutePath(moduleRoute.path); + const pages: RoutePageMenuDef[] = []; + + (moduleRoute.children || []).forEach((child) => { + if (!child.meta || child.meta.hideInMenu) return; + + const routePath = joinRoutePath(parentPath, child.path); + pages.push({ + name: resolveRouteMenuTitle(child), + route: routePath, + component: extractComponentPath(child.component), + permissionCode: (child.meta.permission as string | undefined)?.trim() || undefined, + icon: (child.meta.icon as string | undefined)?.trim() || undefined, + order: (child.meta.order as number | undefined) ?? 0, + isHidden: false, + }); + }); + + return pages.sort((a, b) => a.order - b.order); +} + +export function isModuleMenu(menu: MenuTreeDto): boolean { + if (menu.type !== 1) return false; + + if ((menu.children || []).some((child) => child.type === 1)) { + return true; + } + + const moduleRoute = findModuleRouteByMenu(menu); + return Boolean(moduleRoute?.children?.length); +} + +export function findPageChildMenu( + parent: MenuTreeDto, + routePath: string, + permissionCode?: string, +): MenuTreeDto | undefined { + const normalizedRoute = normalizeRoutePath(routePath); + return (parent.children || []).find((child) => { + if (child.type !== 1) return false; + if (permissionCode && child.permissionCode?.trim() === permissionCode) return true; + if (normalizedRoute && normalizeRoutePath(child.route || '') === normalizedRoute) return true; + return false; + }); +} diff --git a/src/views/channel/autoTrigger/components/FormulaConditionEditor.vue b/src/views/channel/autoTrigger/components/FormulaConditionEditor.vue index db4ed78..36f881e 100644 --- a/src/views/channel/autoTrigger/components/FormulaConditionEditor.vue +++ b/src/views/channel/autoTrigger/components/FormulaConditionEditor.vue @@ -4,7 +4,6 @@ import { FORMULA_MAX_LENGTH, FORMULA_OPERATORS, ORDER_TABLE_CATEGORIES, - OVERSIZE_EXAMPLE_FORMULA, chipsByTable, } from '../formulaMeta' @@ -50,10 +49,6 @@ function onInput(e: Event) { updateValue(val) } -function loadExample() { - updateValue(OVERSIZE_EXAMPLE_FORMULA) -} - watch( () => props.modelValue, (val) => { @@ -63,7 +58,7 @@ watch( } ) -defineExpose({ loadExample, insertAtCursor }) +defineExpose({ insertAtCursor })