From 068d760224a5f6a36e26aa077b3093ea06433571 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 16 Apr 2026 20:00:01 +0800 Subject: [PATCH] feat: sync workspace changes --- .codebuddy/.gitignore | 1 - .cursor/agents/wms-doc-agent.md | 25 +- .github/agents/文档.agent.md | 25 +- AI_TOOLBOX.md | 8 +- README.md | 12 +- app.js | 23 +- app/controller/docs.js | 533 ++++- app/controller/home.js | 148 +- app/extend/application.js | 305 ++- app/lib/order_delivery_selfcheck.js | 19 + app/lib/polo_api_client.js | 235 ++ app/lib/warehouse_shard_guard.js | 93 + app/model/express_platform.js | 75 + app/model/notification_webhook.js | 7 +- app/model/order_delivery.js | 31 +- app/model/order_delivery_factory.js | 704 ++++-- app/model/order_delivery_table_schema.js | 521 +++++ app/model/order_items.js | 5 + app/model/order_items_factory.js | 364 ++- app/model/picking.js | 128 ++ app/model/stock_warehouse.js | 20 + app/model/store.js | 20 + app/model/store_warehouse.js | 147 +- app/router.js | 7 + app/schedule/notice_stock_remaining.js | 733 ++++++ .../sync_outbound_orders_to_delivery.js | 51 + ...ync_outbound_timeout_orders_to_delivery.js | 51 + app/service/qimen.js | 15 +- app/service/qimenMethods/deliveryorder.js | 5 +- app/service/qimenMethods/order.js | 132 +- app/service/systemMethods/index.js | 13 +- .../systemMethods/order/archiveOrder.js | 62 +- app/service/systemMethods/order/base.js | 1181 ++++++++-- .../order/deliveryExpectionOrder.js | 26 + .../systemMethods/order/deliveryOrder.js | 63 +- .../systemMethods/order/entrustOrder.js | 26 + .../systemMethods/order/expectionOrder.js | 90 +- app/service/systemMethods/order/index.js | 239 +- .../systemMethods/order/outboundOrder.js | 34 + .../systemMethods/order/pendingOrder.js | 330 ++- .../systemMethods/order/reviewOrder.js | 133 +- .../systemMethods/order/storageAllocation.js | 47 + app/service/systemMethods/storage/expiry.js | 61 + .../systemMethods/storage/inventory.js | 4 +- app/service/systemMethods/storage/stockout.js | 83 - app/service/systems/delivery_order.js | 273 ++- app/service/systems/excel.js | 26 +- app/service/systems/express.js | 69 + app/service/systems/notice/index.js | 3 + .../systems/order_delivery_migration.js | 643 ++++++ app/service/systems/order_outbound.js | 89 + .../systems/order_pending_exception.js | 43 + .../systems/order_storage_allocation.js | 636 ++++++ app/service/systems/platform.js | 66 + app/service/systems/polo_api.js | 331 ++- app/service/systems/qimen_query.js | 70 +- app/service/systems/stock_store.js | 66 +- app/service/systems/storage/expiry.js | 199 ++ app/service/systems/storage/inventory.js | 290 ++- app/service/systems/storage/receiving.js | 98 + app/service/systems/store.js | 2 + app/service/systems/store_warehouse.js | 15 +- config/plugin.js | 6 +- config/poloapi.js | 29 - ...d-audit-status-to-order-delivery-tables.js | 6 +- ...atus-with-step-on-order-delivery-tables.js | 4 +- ...atus-columns-to-wms-order-delivery-base.js | 30 +- ...-wms-store-subject-config-default-codes.js | 32 + ...0415172000-create-wms-express-interface.js | 74 + .../20260415190000-create-wms-picking.js | 118 + ...60415191000-add-quantity-to-wms-picking.js | 32 + day.log | Bin 37706 -> 0 bytes docs/api-doc-update-spec.example.json | 56 + docs/api-doc-update-workflow.md | 103 + docs/notification-event-api.md | 9 +- docs/notification-webhook-capability.md | 12 +- docs/order-workbench-list-api.md | 186 ++ docs/stock-expiry-module.md | 80 + docs/storage-receiving-api.md | 108 + methods/changes/system.json | 212 +- methods/system.json | 1961 +++++++++++++---- order_todo.md | 69 +- package.json | 3 + .../file-writer/.write-window-counter-3.json | 2 +- .../file-writer/qimen-logs/.consume-progress | 10 +- .../.consume-progress.25476.1775941895725.tmp | 7 + .../qimen-logs-MINGREN-worker-p38224-0001.log | 1 + ...n-logs-MINGREN-worker-p38224-0001.log.done | 7 + .../qimen-logs-MINGREN-worker-p41276-0001.log | 4 + .../qimen-logs-MINGREN-worker-p42648-0001.log | 1 + ...n-logs-MINGREN-worker-p42648-0001.log.done | 7 + script/update-api-doc.cjs | 387 ++++ test/app/controller/docs.test.js | 45 +- ...gateway.user.bindAccountByTempCode.test.js | 14 +- test/app/controller/home.test.js | 99 +- .../qimen.deliveryorder.reviewFlow.test.js | 432 ++++ .../system.order.badgeCount.test.js | 172 ++ .../system.order.getreviewOrderlist.test.js | 92 +- .../system.order.namespaced.test.js | 224 +- .../system.order.outbound.exposure.test.js | 90 + ...er.pendingOrder.reverseReviewOrder.test.js | 613 ++++++ .../system.order.reviewOrder.test.js | 399 +++- ....setting.account.getBindWechatCode.test.js | 14 +- .../system.setting.storeWarehouse.test.js | 11 +- .../system.storage.delivery.module.test.js | 96 +- .../system.storage.inventory.list.test.js | 136 ++ ...tem.storage.inventory.quickPutaway.test.js | 109 +- .../controller/system.storeWarehouse.test.js | 37 + test/app/extend/application.cache.test.js | 238 ++ test/app/lib/order_delivery_selfcheck.test.js | 24 + .../order_delivery_dispatch_factory.test.js | 325 +++ .../order_delivery_factory_selfcheck.test.js | 404 ++++ test/app/model/order_items_factory.test.js | 251 +++ test/app/model/picking.test.js | 80 + .../schedule/notice_stock_remaining.test.js | 448 ++++ .../sync_outbound_orders_to_delivery.test.js | 47 + ...utbound_timeout_orders_to_delivery.test.js | 48 + test/app/service/qimenMethods/order.test.js | 216 ++ .../systemMethods/order.base.step.test.js | 552 ++++- .../order/storageAllocation.test.js | 63 + .../delivery_order.auditStatus.test.js | 93 +- .../systems/delivery_order.oversell.test.js | 42 + test/app/service/systems/excel.test.js | 45 + test/app/service/systems/express.test.js | 118 + test/app/service/systems/notice.test.js | 7 +- .../systems/order_delivery_migration.test.js | 695 ++++++ .../service/systems/order_outbound.test.js | 166 ++ .../systems/order_pending_exception.test.js | 188 ++ .../systems/order_storage_allocation.test.js | 521 +++++ test/app/service/systems/platform.test.js | 118 + test/app/service/systems/polo_api.test.js | 222 ++ test/app/service/systems/qimen_query.test.js | 59 + ...ck_store.stockWarehouse.conditions.test.js | 282 +++ .../service/systems/storage.expiry.test.js | 227 ++ .../service/systems/storage.inventory.test.js | 390 ++++ .../storage.receiving.detailChange.test.js | 127 ++ .../systems/storage.receiving.report.test.js | 185 +- test/support/order_service_test_helper.js | 151 ++ test/support/system_method_client.js | 164 ++ .../20260412-1723-真实下单出库脚本验证报告.md | 44 + ...260414-库存效期任务实例形态回归测试报告.md | 38 + ..._dispatch_factory-MySQL建表集成测试报告.md | 46 + .../20260412-014727-订单工作台list单测报告.md | 53 + .../20260412-165910-订单迁移回归测试报告.md | 35 + .../20260412-1753-真实收货入库流程验证报告.md | 57 + ...º“存效期任务跨天重发与旧缓存兼容验证报告.md | 39 + worktrees/deploy-20260409155126 | 1 - 147 files changed, 20275 insertions(+), 2427 deletions(-) delete mode 100644 .codebuddy/.gitignore create mode 100644 app/lib/order_delivery_selfcheck.js create mode 100644 app/lib/polo_api_client.js create mode 100644 app/lib/warehouse_shard_guard.js create mode 100644 app/model/express_platform.js create mode 100644 app/model/order_delivery_table_schema.js create mode 100644 app/model/picking.js create mode 100644 app/schedule/notice_stock_remaining.js create mode 100644 app/schedule/sync_outbound_orders_to_delivery.js create mode 100644 app/schedule/sync_outbound_timeout_orders_to_delivery.js create mode 100644 app/service/systemMethods/order/deliveryExpectionOrder.js create mode 100644 app/service/systemMethods/order/entrustOrder.js create mode 100644 app/service/systemMethods/order/outboundOrder.js create mode 100644 app/service/systemMethods/order/storageAllocation.js create mode 100644 app/service/systemMethods/storage/expiry.js delete mode 100644 app/service/systemMethods/storage/stockout.js create mode 100644 app/service/systems/express.js create mode 100644 app/service/systems/order_delivery_migration.js create mode 100644 app/service/systems/order_outbound.js create mode 100644 app/service/systems/order_pending_exception.js create mode 100644 app/service/systems/order_storage_allocation.js create mode 100644 app/service/systems/storage/expiry.js delete mode 100644 config/poloapi.js create mode 100644 database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js create mode 100644 database/migrations/20260415172000-create-wms-express-interface.js create mode 100644 database/migrations/20260415190000-create-wms-picking.js create mode 100644 database/migrations/20260415191000-add-quantity-to-wms-picking.js delete mode 100644 day.log create mode 100644 docs/api-doc-update-spec.example.json create mode 100644 docs/api-doc-update-workflow.md create mode 100644 docs/order-workbench-list-api.md create mode 100644 docs/stock-expiry-module.md create mode 100644 runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log create mode 100644 runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done create mode 100644 script/update-api-doc.cjs create mode 100644 test/app/controller/qimen.deliveryorder.reviewFlow.test.js create mode 100644 test/app/controller/system.order.badgeCount.test.js create mode 100644 test/app/controller/system.order.outbound.exposure.test.js create mode 100644 test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js create mode 100644 test/app/controller/system.storage.inventory.list.test.js create mode 100644 test/app/extend/application.cache.test.js create mode 100644 test/app/lib/order_delivery_selfcheck.test.js create mode 100644 test/app/model/order_delivery_dispatch_factory.test.js create mode 100644 test/app/model/order_delivery_factory_selfcheck.test.js create mode 100644 test/app/model/order_items_factory.test.js create mode 100644 test/app/model/picking.test.js create mode 100644 test/app/schedule/notice_stock_remaining.test.js create mode 100644 test/app/schedule/sync_outbound_orders_to_delivery.test.js create mode 100644 test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js create mode 100644 test/app/service/qimenMethods/order.test.js create mode 100644 test/app/service/systemMethods/order/storageAllocation.test.js create mode 100644 test/app/service/systems/express.test.js create mode 100644 test/app/service/systems/order_delivery_migration.test.js create mode 100644 test/app/service/systems/order_outbound.test.js create mode 100644 test/app/service/systems/order_pending_exception.test.js create mode 100644 test/app/service/systems/order_storage_allocation.test.js create mode 100644 test/app/service/systems/platform.test.js create mode 100644 test/app/service/systems/polo_api.test.js create mode 100644 test/app/service/systems/qimen_query.test.js create mode 100644 test/app/service/systems/storage.expiry.test.js create mode 100644 test/app/service/systems/storage.inventory.test.js create mode 100644 test/app/service/systems/storage.receiving.detailChange.test.js create mode 100644 test/support/order_service_test_helper.js create mode 100644 test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md create mode 100644 test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md create mode 100644 test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md create mode 100644 test_reports/pass/20260412-014727-订单工作台list单测报告.md create mode 100644 test_reports/pass/20260412-165910-订单迁移回归测试报告.md create mode 100644 test_reports/pass/20260412-1753-真实收货入库流程验证报告.md create mode 100644 test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md delete mode 160000 worktrees/deploy-20260409155126 diff --git a/.codebuddy/.gitignore b/.codebuddy/.gitignore deleted file mode 100644 index 19e0180..0000000 --- a/.codebuddy/.gitignore +++ /dev/null @@ -1 +0,0 @@ -db/ diff --git a/.cursor/agents/wms-doc-agent.md b/.cursor/agents/wms-doc-agent.md index e6f91f5..f047f74 100644 --- a/.cursor/agents/wms-doc-agent.md +++ b/.cursor/agents/wms-doc-agent.md @@ -38,7 +38,9 @@ is_background: false - 公共请求头变化 - 鉴权方式变化 - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** - - 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况 + - 默认禁止直接手写 `methods/*.json` / `methods/changes/*.json`,必须先按 `docs/api-doc-update-workflow.md` 生成固定 spec,再执行 `npm run doc:api:update -- --spec=` + - 正式写入前必须先执行 `npm run doc:api:update -- --spec= --dry-run` + - 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析的问题 - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` 5. 如 system 入参有变化,可执行: @@ -60,11 +62,11 @@ node .\script\tmp-struct-system-params.cjs ## 推荐工作流 1. 先定位代码真实实现与调用链 -2. 找到对应的 `methods/*.json` / `docs/*.md` -3. 以代码和测试结果为准更新文档 -4. 更新文档后同步追加对应的 `methods/changes/.json` 变更记录 -5. 校验 method 名称、参数、响应与代码一致 -6. 必要时验证 JSON 格式可正常解析 +2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` +3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON +4. 先执行 `npm run doc:api:update -- --spec= --dry-run` +5. 确认后执行 `npm run doc:api:update -- --spec=` 写入 `methods/*.json` 与 `methods/changes/*.json` +6. 再补充 `docs/*.md` / `README.md`,并校验 method 名称、参数、响应与代码一致 ## 常用验证方式 @@ -74,6 +76,12 @@ node .\script\tmp-struct-system-params.cjs node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')" ``` +### 通过固定 spec dry-run 校验 API 文档写入 + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + ### 核对 method 是否已登记 ```powershell @@ -85,8 +93,8 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail ```text 请使用 wms-doc-agent 帮我: 1) 根据代码现状整理接口或业务文档 -2) 同步 methods/*.json / docs/*.md / README -3) 校验文档与实现一致 +2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update +3) 同步 docs/*.md / README,并校验文档与实现一致 ``` ## 输出要求 @@ -95,6 +103,7 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail - 先给结论,再给修改文件、关键字段、验证结果 - 若同步了 `methods/*.json`,明确说明 method 名称与变更点 - 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` +- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果 ## 结论 diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md index b89f2e3..be3c5df 100644 --- a/.github/agents/文档.agent.md +++ b/.github/agents/文档.agent.md @@ -38,7 +38,9 @@ model: GPT-5 mini (copilot) - 公共请求头变化 - 鉴权方式变化 - 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** - - 修补json文件时必须强校验 JSON格式的正确性,确保不会引入格式错误导致无法解析的情况 + - 默认禁止直接手写 `methods/*.json` / `methods/changes/*.json`,必须先按 `docs/api-doc-update-workflow.md` 生成固定 spec,再执行 `npm run doc:api:update -- --spec=` + - 正式写入前必须先执行 `npm run doc:api:update -- --spec= --dry-run` + - 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析的问题 - `methods/*.json` 仍是 SSOT,`methods/changes/*.json` 仅记录差异历史 - 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes` 5. 如 system 入参有变化,可执行: @@ -60,11 +62,11 @@ node .\script\tmp-struct-system-params.cjs ## 推荐工作流 1. 先定位代码真实实现与调用链 -2. 找到对应的 `methods/*.json` / `docs/*.md` -3. 以代码和测试结果为准更新文档 -4. 更新文档后同步追加对应的 `methods/changes/.json` 变更记录 -5. 校验 method 名称、参数、响应与代码一致 -6. 必要时验证 JSON 格式可正常解析 +2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` +3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON +4. 先执行 `npm run doc:api:update -- --spec= --dry-run` +5. 确认后执行 `npm run doc:api:update -- --spec=` 写入 `methods/*.json` 与 `methods/changes/*.json` +6. 再补充 `docs/*.md` / `README.md`,并校验 method 名称、参数、响应与代码一致 ## 常用验证方式 @@ -74,6 +76,12 @@ node .\script\tmp-struct-system-params.cjs node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')" ``` +### 通过固定 spec dry-run 校验 API 文档写入 + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + ### 核对 method 是否已登记 ```powershell @@ -85,8 +93,8 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail ```text 请使用 wms-doc-agent 帮我: 1) 根据代码现状整理接口或业务文档 -2) 同步 methods/*.json / docs/*.md / README -3) 校验文档与实现一致 +2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update +3) 同步 docs/*.md / README,并校验文档与实现一致 ``` ## 输出要求 @@ -95,6 +103,7 @@ Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetail - 先给结论,再给修改文件、关键字段、验证结果 - 若同步了 `methods/*.json`,明确说明 method 名称与变更点 - 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` +- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果 ## 结论 diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 2327c12..3a849df 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -101,8 +101,8 @@ GitHub Copilot 读取 `.github/agents/*.agent.md`;Cursor 使用 `.cursor/agent ```text 请使用 wms-doc-agent 帮我: 1) 根据代码现状整理接口或业务文档 -2) 同步 methods/*.json / docs/*.md / README -3) 校验文档与实现一致 +2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update +3) 同步 docs/*.md / README,并校验 methods/*.json 与 methods/changes/*.json 可解析 ``` ### 3.6 混合任务 / 不确定归属(强制走 Dispatcher) @@ -196,7 +196,9 @@ Redis 相关能力文档已统一移交给 `wms-redis-agent`。 执行要求(强制): - **涉及文档编写或同步的任何问题,必须使用 `wms-doc-agent`** - 文档必须以代码实现、测试结果和现有 JSON 文档为准,不得凭空编写 -- system 参数变化可执行:`node .\script\tmp-struct-system-params.cjs` +- 默认禁止直接手写 `methods/*.json` 和 `methods/changes/*.json`;必须先按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 组织 spec,再执行 `npm run doc:api:update -- --spec=` +- system 参数变化可先执行:`node .\script\tmp-struct-system-params.cjs` +- 正式写入前必须先执行:`npm run doc:api:update -- --spec= --dry-run` - 具体工作流统一见:`.github/agents/文档.agent.md` ## 9. 测试能力移交规则 diff --git a/README.md b/README.md index 60348dc..09584fc 100644 --- a/README.md +++ b/README.md @@ -100,14 +100,20 @@ npm run dev 建议流程: 1. 先完成代码改动(controller/service/model) -2. 同步维护 `methods/system.json` 或 `methods/qimen.json` -3. system 参数改动后执行: +2. 按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 复制固定 spec 到 `temp/`,默认通过 `npm run doc:api:update -- --spec=...` 写入 `methods/*.json` +3. system 参数改动后可先执行: ```powershell node .\script\tmp-struct-system-params.cjs ``` -4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束) +4. 先执行: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + +5. 确认无误后执行正式写入,再补充自动提取无法覆盖的信息(description/response/errors/枚举约束) ## 配置说明 diff --git a/app.js b/app.js index a40e349..14bed0b 100644 --- a/app.js +++ b/app.js @@ -1,6 +1,7 @@ // app.js const path = require('path'); const LocalFileWriter = require('./app/lib/file_writer'); +const ensureOrderDeliverySelfCheck = require('./app/lib/order_delivery_selfcheck'); /** * 挂载应用级扩展能力。 @@ -16,30 +17,36 @@ module.exports = app => { app.logger.info('✅ fileWriter 已挂载到 app.fileWriter'); // 初始化工厂 app.beforeStart(async () => { - // skip factory init when model layer is absent (e.g. during tests) + const OrderDeliveryFactory = require('./app/model/order_delivery_factory'); + app.OrderDeliveryFactory = OrderDeliveryFactory(app); + + // skip 热区工厂 when model layer is absent (e.g. 部分单测) if (!app.model) { - app.logger.info('⚠️ skipping factory init: app.model not available'); + app.logger.info('⚠️ skipping OrderDelivery/OrderItems factory init: app.model not available'); return; } + try { - const OrderDeliveryFactory = require('./app/model/order_delivery_factory'); const OrderItemsFactory = require('./app/model/order_items_factory'); - app.OrderDeliveryFactory = OrderDeliveryFactory(app); app.model.OrderDeliveryFactory = app.OrderDeliveryFactory; app.OrderItemsFactory = OrderItemsFactory(app); app.model.OrderItemsFactory = app.OrderItemsFactory; app.logger.info('✅ 工厂类初始化完成'); + //await ensureOrderDeliverySelfCheck(app); } catch (error) { - app.logger.error('❌ 工厂类初始化失败:', error); } + // 验证缓存方法 if (typeof app.setCacheAsync === 'function') { - app.setCacheAsync('system', 'eggjs'); + await app.setCacheAsync('system', 'wms', 10); const system = await app.getCacheAsync('system'); - app.logger.info('✅ 缓存方法验证通过' + system); + if (system !== 'wms') { + app.logger.error('❌ 缓存方法验证失败: setCacheAsync/getCacheAsync 不一致'); + } else { + app.logger.info(`✅ 缓存方法验证通过${system}`); + } } - app.logger.info('✅ l类型' + typeof app.Message); }); }; diff --git a/app/controller/docs.js b/app/controller/docs.js index d6425ea..b0a247d 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -13,6 +13,97 @@ function escapeHtml(value) { .replace(/'/g, '''); } +/** + * 清洗 window 标签使用的跳转地址,避免注入危险协议或控制字符。 + * @param {string} value 待清洗的地址。 + * @return {string} 允许使用的地址,非法时返回空字符串。 + */ +function sanitizeWindowHref(value) { + const href = String(value || '').trim(); + if (!href) { + return ''; + } + + const hasControlCharacter = Array.from(href).some(character => { + const code = character.charCodeAt(0); + return code <= 0x1f || code === 0x7f; + }); + if (hasControlCharacter || /^(javascript|data|vbscript):/i.test(href)) { + return ''; + } + + return href; +} + +/** + * 从 window 标签属性中提取跳转地址。 + * @param {string} attributeText 标签属性文本。 + * @return {string} 提取到的地址,未找到时返回空字符串。 + */ +function extractWindowHref(attributeText) { + const attributes = String(attributeText || ''); + const match = attributes.match(/(?:href|data-href|data-window-href)\s*=\s*("([^"]*)"|'([^']*)')/i); + if (!match) { + return ''; + } + + return match[2] || match[3] || ''; +} + +/** + * 渲染可点击的 window 自定义元素。 + * @param {string} label 元素展示文案。 + * @param {string} href 点击后打开的地址。 + * @param {string} [className] 额外样式类名。 + * @return {string} 生成的 HTML 片段。 + */ +function renderWindowElement(label, href, className = '') { + const safeHref = sanitizeWindowHref(href); + const safeLabel = escapeHtml(label || safeHref); + if (!safeHref) { + return safeLabel; + } + + const classes = [ 'window-link' ]; + if (className) { + classes.push(className); + } + + return `${safeLabel}`; +} + +/** + * 将文本中的 标签安全渲染为可点击元素。 + * @param {string} value 原始文本。 + * @return {string} 处理后的 HTML。 + */ +function renderTextWithWindowTags(value) { + const text = String(value || ''); + if (!text.includes(']*)>([\s\S]*?)<\/window>/gi; + let lastIndex = 0; + let rendered = ''; + let match; + + while ((match = pattern.exec(text)) !== null) { + rendered += escapeHtml(text.slice(lastIndex, match.index)); + + const attributes = match[1] || ''; + const content = match[2] || ''; + const href = sanitizeWindowHref(extractWindowHref(attributes) || content.trim()); + const label = content.trim() || href; + + rendered += renderWindowElement(label, href); + lastIndex = pattern.lastIndex; + } + + rendered += escapeHtml(text.slice(lastIndex)); + return rendered; +} + function toArray(value) { return Array.isArray(value) ? value : []; } @@ -36,6 +127,302 @@ function getDocChangesFilePath(app, docName) { return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`); } +/** + * 获取 docs 目录的绝对路径。 + * @param {Egg.Application} app Egg 应用实例。 + * @return {string} docs 根目录绝对路径。 + */ +function getDocsRootPath(app) { + return path.resolve(app.baseDir, 'docs'); +} + +/** + * 递归解码 URL 路径片段,尽量还原编码穿越路径。 + * @param {string} input 待解码的路径片段。 + * @return {string|null} 解码后的路径片段,解码失败时返回 null。 + */ +function decodeDocsPath(input) { + let value = String(input || '').trim(); + if (!value) { + return ''; + } + + for (let index = 0; index < 3; index += 1) { + try { + const decoded = decodeURIComponent(value); + if (decoded === value) { + break; + } + value = decoded; + } catch (error) { + return null; + } + } + + return value; +} + +/** + * 将 docs 相对路径转换为可访问 URL。 + * @param {string} relativePath docs 相对路径。 + * @return {string} 可直接用于 href 的路径。 + */ +function toDocsHref(relativePath) { + return String(relativePath || '') + .split(/[\\/]+/) + .filter(Boolean) + .map(segment => encodeURIComponent(segment)) + .join('/'); +} + +/** + * 按扩展名返回 docs 文件的响应类型。 + * @param {string} filePath 文件绝对路径。 + * @return {string} Content-Type 值。 + */ +function getDocsContentType(filePath) { + const ext = path.extname(filePath).toLowerCase(); + if (ext === '.md' || ext === '.markdown') { + return 'text/markdown; charset=utf-8'; + } + + if (ext === '.json') { + return 'application/json; charset=utf-8'; + } + + return 'text/plain; charset=utf-8'; +} + +/** + * 解析并校验 docs 文件路径,阻止路径穿越。 + * @param {Egg.Application} app Egg 应用实例。 + * @param {string} relativePath docs 相对路径。 + * @return {{ ok: boolean, filePath?: string, relativePath?: string, message?: string }} 解析结果。 + */ +function resolveDocsFilePath(app, relativePath) { + const decodedPath = decodeDocsPath(relativePath); + if (decodedPath === null || !decodedPath) { + return { + ok: false, + message: '无效文档路径', + }; + } + + if (decodedPath.includes('\\') || path.isAbsolute(decodedPath)) { + return { + ok: false, + message: '无效文档路径', + }; + } + + const docsRootPath = getDocsRootPath(app); + const filePath = path.resolve(docsRootPath, decodedPath); + const relativeToRoot = path.relative(docsRootPath, filePath); + + if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) { + return { + ok: false, + message: '路径越界', + }; + } + + return { + ok: true, + filePath, + relativePath: decodedPath, + }; +} + +/** + * 递归收集 docs 目录下的所有文件。 + * @param {string} dirPath 当前扫描目录。 + * @param {string} baseDir docs 根目录。 + * @return {Promise>} 文件列表。 + */ +async function collectDocsFiles(dirPath, baseDir) { + const entries = await fs.readdir(dirPath, { withFileTypes: true }); + const files = []; + + for (const entry of entries) { + const entryPath = path.join(dirPath, entry.name); + if (entry.isDirectory()) { + const nestedFiles = await collectDocsFiles(entryPath, baseDir); + files.push(...nestedFiles); + continue; + } + + if (entry.isFile()) { + files.push({ + relativePath: path.relative(baseDir, entryPath), + filePath: entryPath, + }); + } + } + + return files; +} + +/** + * 生成 docs 索引页 HTML。 + * @param {Array<{ relativePath: string }>} files docs 文件列表。 + * @return {string} HTML 文档。 + */ +function renderDocsIndexPage(files) { + const listHtml = files.length + ? files.map(file => { + const href = `/docs/${toDocsHref(file.relativePath)}`; + return `
  • ${renderWindowElement(file.relativePath, href, 'doc-file-link')}
  • `; + }).join('') + : '
  • docs 目录下暂无文件
  • '; + + return ` + + + + + Docs 索引 + + + +
    +
    +

    docs 目录索引

    +

    以下文件来自 docs 根目录,点击即可直接查看对应内容。

    +
      ${listHtml}
    +
    +
    + + +`; +} + +/** + * 生成 docs 文件内容响应。 + * @param {Egg.Context} ctx 当前请求上下文。 + * @param {string} filePath 文件绝对路径。 + * @return {Promise} 无返回值。 + */ +async function sendDocsFile(ctx, filePath) { + const content = await fs.readFile(filePath, 'utf8'); + ctx.set('Content-Type', getDocsContentType(filePath)); + ctx.body = content; +} + function normalizeGroups(docData) { if (docData && docData.methods && Array.isArray(docData.methods.groups)) { return docData.methods.groups.map(group => ({ @@ -56,6 +443,12 @@ function normalizeGroups(docData) { return []; } +/** + * 渲染键值表格。 + * @param {Array} items 数据项列表。 + * @param {{ name: string, type: string, required: string, description: string }} keyMap 字段映射。 + * @return {string} 表格行 HTML。 + */ function renderKeyValueRows(items, keyMap) { if (!items.length) { return '暂无数据'; @@ -66,11 +459,16 @@ function renderKeyValueRows(items, keyMap) { ${escapeHtml(item[keyMap.name] || '')} ${escapeHtml(item[keyMap.type] || '')} ${item[keyMap.required] ? '是' : '否'} - ${escapeHtml(item[keyMap.description] || '')} + ${renderTextWithWindowTags(item[keyMap.description] || '')} `; }).join(''); } +/** + * 渲染全局 Header 控件区域。 + * @param {Array} globalHeaders 全局 Header 定义。 + * @return {string} HTML 片段。 + */ function renderGlobalHeadersControls(globalHeaders) { const headers = toArray(globalHeaders); if (!headers.length) { @@ -94,11 +492,18 @@ function renderGlobalHeadersControls(globalHeaders) { return ``; }).join('')}`; } +/** + * 渲染单个接口卡片。 + * @param {object} item 接口定义。 + * @param {string} entryPath 统一入口路径。 + * @param {string} moduleName 文档所属模块名。 + * @return {string} HTML 片段。 + */ function renderMethodCard(item, entryPath, moduleName) { const headers = toArray(item.headers); const params = toArray(item.params); @@ -115,7 +520,7 @@ function renderMethodCard(item, entryPath, moduleName) {

    ${escapeHtml(methodName)}

    -

    ${escapeHtml(description)}

    +

    ${renderTextWithWindowTags(description)}

    入口: ${escapeHtml(entryPath)} @@ -196,6 +601,11 @@ function renderMethodCard(item, entryPath, moduleName) { `; } +/** + * 渲染 API 文档页面。 + * @param {{ docName: string, docData: object, groups: Array, docs: Array, entryPath: string }} options 渲染参数。 + * @return {string} HTML 文档。 + */ function renderHtmlPage({ docName, docData, @@ -446,6 +856,20 @@ function renderHtmlPage({ background: #eef5ff; color: #123e79; } + .window-link { + display: inline-flex; + align-items: center; + gap: 4px; + cursor: pointer; + user-select: none; + } + .window-link:hover { + text-decoration: underline; + } + .window-link:focus { + outline: 2px solid #8fb4ea; + outline-offset: 2px; + } .doc-content { min-width: 0; } @@ -590,8 +1014,8 @@ function renderHtmlPage({

    文档资源

    - 打开变更记录 - 打开原文 JSON + ${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')} + ${renderWindowElement('打开原文 JSON', rawUrl, 'doc-resource-link')}
    @@ -633,6 +1057,19 @@ function renderHtmlPage({ var changesUrl = ${JSON.stringify(changesUrl)}; var rawUrl = ${JSON.stringify(rawUrl)}; + function openWindowHref(target) { + var href = target && target.getAttribute('data-window-href'); + if (!href) { + return; + } + + var popup = window.open(href, '_blank', 'noopener,noreferrer'); + if (popup) { + popup.opener = null; + popup.focus(); + } + } + function nowTimestamp() { return Math.floor(Date.now() / 1000); } @@ -850,6 +1287,30 @@ function renderHtmlPage({ }); } + document.addEventListener('click', function(event) { + var target = event.target.closest('[data-window-href]'); + if (!target) { + return; + } + + event.preventDefault(); + openWindowHref(target); + }); + + document.addEventListener('keydown', function(event) { + var target = event.target.closest('[data-window-href]'); + if (!target) { + return; + } + + if (event.key !== 'Enter' && event.key !== ' ') { + return; + } + + event.preventDefault(); + openWindowHref(target); + }); + document.addEventListener('click', async function(event) { var btn = event.target.closest('.send-btn'); if (!btn) return; @@ -927,6 +1388,68 @@ function renderHtmlPage({ } class DocsController extends Controller { + /** + * 返回 docs 目录索引页面。 + * @return {Promise} 无返回值。 + */ + async docsIndex() { + const { ctx } = this; + + try { + const docsRootPath = getDocsRootPath(this.app); + const files = await collectDocsFiles(docsRootPath, docsRootPath); + files.sort((left, right) => left.relativePath.localeCompare(right.relativePath, 'zh-Hans-CN')); + ctx.set('Content-Type', 'text/html; charset=utf-8'); + ctx.body = renderDocsIndexPage(files); + } catch (error) { + ctx.status = 500; + ctx.body = { + code: 500, + message: '读取 docs 目录失败', + error: error.message, + }; + } + } + + /** + * 读取 docs 目录下的指定文件。 + * @return {Promise} 无返回值。 + */ + async docsFile() { + const { ctx } = this; + const rawRelativePath = ctx.params[0] || ctx.params.relPath || ctx.params.path || ''; + const resolved = resolveDocsFilePath(this.app, rawRelativePath); + + if (!resolved.ok) { + ctx.status = 400; + ctx.body = { + code: 400, + message: resolved.message || '无效文档路径', + }; + return; + } + + try { + await sendDocsFile(ctx, resolved.filePath); + } catch (error) { + if (error.code === 'ENOENT') { + ctx.status = 404; + ctx.body = { + code: 404, + message: `未找到 docs 文件: ${resolved.relativePath}`, + }; + return; + } + + ctx.status = 500; + ctx.body = { + code: 500, + message: '读取 docs 文件失败', + error: error.message, + }; + } + } + async list() { const { ctx } = this; try { diff --git a/app/controller/home.js b/app/controller/home.js index c3d192c..03d0809 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -9,12 +9,29 @@ class HomeController extends Controller { await this.ctx.service.systems.print.index.test(); this.ctx.body = 'ok'; } + /** + * Polo API 测试入口,直接透传 PoloApiService.test() 的真实返回结果。 + * + * @return {Promise} 无返回值,响应结果直接写入 ctx.body。 + */ + async testPoloApi() { + const { + ctx, + } = this; + + const result = await ctx.service.systems.poloApi.test(); + ctx.body = result; + } async index() { const { ctx, } = this; ctx.body = 'pong'; } + /** + * 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。 + * @return {Promise} 无返回值。 + */ async qimen() { const { ctx, @@ -97,7 +114,16 @@ class HomeController extends Controller { // 解析XML数据 const xmlArray = await service.qimen.parseXmlToArray(xmlData); xmlArray.app_key = appkey; - let warehouseCode = xmlArray.request.warehouseCode || ''; + const warehouseCode = this.getQimenWarehouseCode(xmlArray); + + if (!warehouseCode) { + const errorMsg = 'XML数据格式错误,无法提取有效的warehouseCode'; + const responseFormat = getParams.format || 'xml'; + const response = this.errorResponse(errorMsg, responseFormat); + ctx.body = response; + ctx.type = responseFormat === 'xml' ? 'application/xml' : 'application/json'; + return; + } logData.body = xmlData; const erpName = await service.qimen.getErpName(appkey); @@ -105,16 +131,6 @@ class HomeController extends Controller { warehouseCode: '', ownerCode: '', }; - if (!warehouseCode || !customerId) { - // 入库单提取 - try { - warehouseCode = xmlArray.request?.entryOrder?.warehouseCode || - xmlArray.request?.deliveryOrder?.warehouseCode || - ''; - } catch (e) { - throw new Error('XML数据格式错误,无法提取warehouseCode'); - } - } if (warehouseCode && customerId) { // 验证接口是否存在且启用 api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode); @@ -187,6 +203,116 @@ class HomeController extends Controller { } } + /** + * 归一化奇门字段值,过滤空白内容和占位符字符串。 + * @param {string|number|null|undefined} value 待处理字段值。 + * @return {string} 归一化后的字段值。 + */ + normalizeQimenFieldValue(value) { + if (value === null || value === undefined) { + return ''; + } + + const normalizedValue = String(value).trim(); + if (!normalizedValue || normalizedValue === 'warehouseCode') { + return ''; + } + + return normalizedValue; + } + + /** + * 递归扫描奇门 XML 树,提取指定字段的有效值,只匹配字段名对应的节点。 + * @param {Object|Array|string|number|null|undefined} node 待扫描节点。 + * @param {string} fieldName 目标字段名。 + * @param {Set} [visited=new Set()] 循环引用保护集合。 + * @return {string} 找到的有效字段值。 + */ + findQimenFieldValue(node, fieldName, visited = new Set()) { + if (node === null || node === undefined) { + return ''; + } + + if (typeof node !== 'object') { + return ''; + } + + if (visited.has(node)) { + return ''; + } + + visited.add(node); + + if (Array.isArray(node)) { + for (const item of node) { + const value = this.findQimenFieldValue(item, fieldName, visited); + if (value) { + return value; + } + } + return ''; + } + + if (Object.prototype.hasOwnProperty.call(node, fieldName)) { + const directValue = this.normalizeQimenFieldValue(node[fieldName]); + if (directValue) { + return directValue; + } + + const nestedValue = this.findQimenFieldValue(node[fieldName], fieldName, visited); + if (nestedValue) { + return nestedValue; + } + } + + for (const [ key, value ] of Object.entries(node)) { + if (key === fieldName) { + continue; + } + + if (value === null || value === undefined) { + continue; + } + + if (typeof value !== 'object') { + continue; + } + + const foundValue = this.findQimenFieldValue(value, fieldName, visited); + if (foundValue) { + return foundValue; + } + } + + return ''; + } + + /** + * 从奇门请求体中提取有效的仓库编码,优先读取 request 下的固定路径,再回退到递归扫描。 + * @param {Object} xmlArray 解析后的 XML 数据。 + * @return {string} 有效的仓库编码。 + */ + getQimenWarehouseCode(xmlArray) { + const request = xmlArray?.request || xmlArray || {}; + + const fixedPaths = [ + request?.deliveryOrder?.warehouseCode, + request?.entryOrder?.warehouseCode, + request.warehouseCode, + ]; + + for (const value of fixedPaths) { + const normalizedValue = this.normalizeQimenFieldValue(value); + if (normalizedValue) { + return normalizedValue; + } + } + + return this.findQimenFieldValue(request, 'warehouseCode') + || this.findQimenFieldValue(xmlArray, 'warehouseCode') + || ''; + } + validateParams(params) { const required = [ 'method', 'v', 'format', 'timestamp' ]; diff --git a/app/extend/application.js b/app/extend/application.js index e3c55da..837fd75 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -1,5 +1,219 @@ const soap = require('soap'); const businessDict = require('../dict/businessDict'); + +const LOCAL_CACHE_CLEANUP_INTERVAL_MS = 60 * 1000; +const LOCAL_CACHE_STATE_KEY = '__wmsLocalCacheState'; + +/** + * 获取缓存日志记录器。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} 日志对象。 + */ +function getCacheLogger(app) { + return app && (app.logger || app.coreLogger) ? (app.logger || app.coreLogger) : null; +} + +/** + * 获取或初始化进程内缓存状态。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} 进程内缓存状态。 + */ +function getLocalCacheState(app) { + if (!app) { + return null; + } + + if (!app[LOCAL_CACHE_STATE_KEY]) { + app[LOCAL_CACHE_STATE_KEY] = { + store: new Map(), + cleanupTimer: null, + lastCleanupAt: 0, + }; + } + + return app[LOCAL_CACHE_STATE_KEY]; +} + +/** + * 规范化缓存过期秒数。 + * + * @param {*} expireSeconds 过期秒数。 + * @return {number} 规范化后的秒数。 + */ +function normalizeExpireSeconds(expireSeconds) { + const ttl = Number(expireSeconds); + if (!Number.isFinite(ttl) || ttl <= 0) { + return 0; + } + return Math.floor(ttl); +} + +/** + * 复制缓存值,避免进程内缓存被外部引用直接修改。 + * + * @param {*} value 缓存值。 + * @return {*} 复制后的缓存值。 + */ +function cloneCacheValue(value) { + if (value === null || value === undefined) { + return value; + } + + try { + return JSON.parse(JSON.stringify(value)); + } catch (error) { + return value; + } +} + +/** + * 清理已经过期的进程内缓存。 + * + * @param {Object} state 进程内缓存状态。 + * @return {number} 清理的条目数。 + */ +function cleanupLocalCache(state) { + if (!state || !state.store) { + return 0; + } + + const now = Date.now(); + let removedCount = 0; + + for (const [ cacheKey, cacheEntry ] of state.store.entries()) { + if (!cacheEntry || cacheEntry.expireAt <= now) { + state.store.delete(cacheKey); + removedCount += 1; + } + } + + state.lastCleanupAt = now; + return removedCount; +} + +/** + * 启动进程内缓存的定时清理任务。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} 进程内缓存状态。 + */ +function ensureLocalCacheCleanupTimer(app) { + const state = getLocalCacheState(app); + if (!state || state.cleanupTimer) { + return state; + } + + state.cleanupTimer = setInterval(() => { + cleanupLocalCache(state); + }, LOCAL_CACHE_CLEANUP_INTERVAL_MS); + + if (state.cleanupTimer && typeof state.cleanupTimer.unref === 'function') { + state.cleanupTimer.unref(); + } + + return state; +} + +/** + * 获取 Redis 缓存客户端。 + * + * @param {Object} app 应用实例。 + * @return {Object|null} Redis 缓存客户端。 + */ +function getRedisCacheClient(app) { + try { + return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null; + } catch (error) { + const logger = getCacheLogger(app); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisUnavailable] 获取 Redis 缓存客户端失败', error.message); + } + return null; + } +} + +/** + * 将值写入进程内缓存。 + * + * @param {Object} app 应用实例。 + * @param {string} cacheKey 缓存键。 + * @param {*} data 缓存数据。 + * @param {number} expireSeconds 过期秒数。 + */ +function setLocalCacheValue(app, cacheKey, data, expireSeconds) { + const state = ensureLocalCacheCleanupTimer(app); + if (!state) { + return; + } + + const ttl = normalizeExpireSeconds(expireSeconds); + if (ttl <= 0) { + state.store.delete(cacheKey); + return; + } + + state.store.set(cacheKey, { + value: cloneCacheValue(data), + expireAt: Date.now() + (ttl * 1000), + }); +} + +/** + * 从进程内缓存读取值。 + * + * @param {Object} app 应用实例。 + * @param {string} cacheKey 缓存键。 + * @return {*} 缓存值或 null。 + */ +function getLocalCacheValue(app, cacheKey) { + const state = getLocalCacheState(app); + if (!state) { + return null; + } + + const cacheEntry = state.store.get(cacheKey); + if (!cacheEntry) { + return null; + } + + if (cacheEntry.expireAt <= Date.now()) { + state.store.delete(cacheKey); + return null; + } + + return cloneCacheValue(cacheEntry.value); +} + +/** + * 从进程内缓存删除值。 + * + * @param {Object} app 应用实例。 + * @param {string} cacheKey 缓存键。 + */ +function deleteLocalCacheValue(app, cacheKey) { + const state = getLocalCacheState(app); + if (!state) { + return; + } + + state.store.delete(cacheKey); +} + +/** + * 将 Redis 返回的数据解析为对象。 + * + * @param {string} cacheValue Redis 缓存字符串。 + * @return {*} 解析后的值。 + */ +function parseRedisCacheValue(cacheValue) { + if (cacheValue === undefined || cacheValue === null) { + return null; + } + + return JSON.parse(cacheValue); +} module.exports = { get businessDict() { return businessDict; @@ -50,40 +264,83 @@ module.exports = { const result = await client[methodName + 'Async'](obj); return result[0]; } catch (error) { - console.error('Error calling SOAP service:', error); throw error; } }, + /** + * 写入缓存。 + * + * Redis 可用时优先写入 Redis;当 Redis 不可用或写入失败时,自动降级到进程内缓存。 + * + * @param {string} cacheKey 缓存键。 + * @param {*} data 缓存数据。 + * @param {number} [expireSeconds=300] 过期秒数。 + * @return {Promise} + */ async setCacheAsync(cacheKey, data, expireSeconds = 300) { - const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null; - if (!cacheRedis) { - this.logger.warn('[RedisNotAvailable] Cannot set cache, Redis client is not available'); + const ttl = normalizeExpireSeconds(expireSeconds); + const cacheRedis = getRedisCacheClient(this); + + if (ttl <= 0) { + if (cacheRedis && typeof cacheRedis.del === 'function') { + try { + await cacheRedis.del(cacheKey); + } catch (error) { + const logger = getCacheLogger(this); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey); + } + } + } + + deleteLocalCacheValue(this, cacheKey); return; } - try { - await cacheRedis.setex(cacheKey, expireSeconds, JSON.stringify(data)); - this.logger.debug('[CacheSet] Successfully set cache', cacheKey); - } catch (error) { - this.logger.error('[CacheSetError] Failed to set cache', error.message, cacheKey); - } - }, - async getCacheAsync(cacheKey) { - const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null; - if (!cacheRedis) { - this.logger.warn('[RedisNotAvailable] Cannot get cache, Redis client is not available'); - return null; + if (cacheRedis && typeof cacheRedis.setex === 'function') { + try { + await cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)); + + setLocalCacheValue(this, cacheKey, data, ttl); + + return; + } catch (error) { + const logger = getCacheLogger(this); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisSetError] Redis 写入缓存失败,已降级到进程内缓存', error.message, cacheKey); + } + } } - try { - const data = await cacheRedis.get(cacheKey); - if (data) { - return JSON.parse(data); + setLocalCacheValue(this, cacheKey, data, ttl); + }, + /** + * 读取缓存。 + * + * Redis 可用时优先读取 Redis;当 Redis 不可用、读取失败或命中为空时,自动回退到进程内缓存。 + * + * @param {string} cacheKey 缓存键。 + * @return {Promise<*>} 缓存数据,未命中时返回 null。 + */ + async getCacheAsync(cacheKey) { + const cacheRedis = getRedisCacheClient(this); + + if (cacheRedis && typeof cacheRedis.get === 'function') { + try { + const data = await cacheRedis.get(cacheKey); + if (data === undefined || data === null) { + return null; + } + + return parseRedisCacheValue(data); + } catch (error) { + const logger = getCacheLogger(this); + if (logger && typeof logger.warn === 'function') { + logger.warn('[CacheRedisGetError] Redis 读取缓存失败,已回退到进程内缓存', error.message, cacheKey); + } } - return null; - } catch (error) { - this.logger.error('[CacheGetError] Failed to get cache', error.message, cacheKey); - return null; } + + return getLocalCacheValue(this, cacheKey); }, }; diff --git a/app/lib/order_delivery_selfcheck.js b/app/lib/order_delivery_selfcheck.js new file mode 100644 index 0000000..d7cd83b --- /dev/null +++ b/app/lib/order_delivery_selfcheck.js @@ -0,0 +1,19 @@ +'use strict'; + +/** + * 在应用启动阶段触发订单发货表的 managed table schema 自检。 + * @param {import('egg').Application} app 应用实例。 + * @return {Promise} + */ +module.exports = async app => { + if (!app || !app.OrderDeliveryFactory) { + return; + } + + if (typeof app.OrderDeliveryFactory.ensureManagedTableSchemas !== 'function') { + return; + } + + await app.OrderDeliveryFactory.ensureManagedTableSchemas(); + app.logger.info('✅ 订单工厂目标表自检完成'); +}; diff --git a/app/lib/polo_api_client.js b/app/lib/polo_api_client.js new file mode 100644 index 0000000..4fb67ba --- /dev/null +++ b/app/lib/polo_api_client.js @@ -0,0 +1,235 @@ +'use strict'; + +const crypto = require('crypto'); + +const POLYAPI_CONFIG_CACHE_KEY = 'polo_api_client:polyapi:config'; +const POLYAPI_CONFIG_CACHE_TTL_SECONDS = 60 * 60; + +/** + * PolyAPI 底层 HTTP 客户端。 + * 封装签名、表单编码、请求发送等通用逻辑,与业务无关。 + */ +class PoloApiClient { + /** + * @param {object} ctx - Egg 上下文对象。 + */ + constructor(ctx) { + this.ctx = ctx; + this._config = null; + this._configPromise = null; + this.contenttype = 'json'; + } + + /** + * 按需加载并缓存 PolyAPI 配置。 + * + * 优先读取应用级缓存;缓存未命中或读取失败时,再回源数据库。 + * 数据库查到配置后,会回写到应用级缓存,缓存 TTL 为 1 小时。 + * + * @returns {Promise} PolyAPI 配置记录。 + */ + async getConfig(platid) { + if (this._config) { + return this._config; + } + + if (!this._configPromise) { + this._configPromise = this._loadConfig(platid).then(config => { + this._config = config || null; + return this._config; + }).finally(() => { + this._configPromise = null; + }); + } + + return this._configPromise; + } + + /** + * 读取 PolyAPI 配置:先查缓存,未命中则查数据库。 + * + * @returns {Promise} PolyAPI 配置记录。 + */ + async _loadConfig(platid) { + const cachedConfig = await this._getCachedConfig(platid); + if (cachedConfig) { + return cachedConfig; + } + + const config = await this._loadConfigFromDatabase(platid); + if (config) { + await this._setCachedConfig(config); + } + + return config; + } + + /** + * 从应用级缓存读取 PolyAPI 配置。 + * + * 缓存读取失败时,返回 null 并由调用方继续回源数据库。 + * + * @returns {Promise} 缓存中的配置记录。 + */ + async _getCachedConfig(platid) { + if (!this.ctx.app || typeof this.ctx.app.getCacheAsync !== 'function') { + return null; + } + + try { + return await this.ctx.app.getCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${platid}`); + } catch (error) { + if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') { + this.ctx.logger.warn('[PoloApiClient._getCachedConfig] 读取缓存失败,回退数据库查询: %s', error.message); + } + + return null; + } + } + + /** + * 查询数据库中的 PolyAPI 配置。 + * + * @returns {Promise} 数据库中的配置记录。 + */ + async _loadConfigFromDatabase(platid) { + if (!this.ctx.app || !this.ctx.app.model || !this.ctx.app.model.ExpressPlatform || typeof this.ctx.app.model.ExpressPlatform.findOne !== 'function') { + return null; + } + + return await this.ctx.app.model.ExpressPlatform.findOne({ + where: { platid: platid }, + }); + } + + /** + * 将 PolyAPI 配置写回应用级缓存。 + * + * @param {object} config - PolyAPI 配置记录。 + * @returns {Promise} + */ + async _setCachedConfig(config) { + if (!this.ctx.app || typeof this.ctx.app.setCacheAsync !== 'function') { + return; + } + + try { + const cacheValue = config && typeof config.toJSON === 'function' ? config.toJSON() : config; + await this.ctx.app.setCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${config.platid}`, cacheValue, POLYAPI_CONFIG_CACHE_TTL_SECONDS); + } catch (error) { + if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') { + this.ctx.logger.warn('[PoloApiClient._setCachedConfig] 写入缓存失败,继续使用数据库结果: %s', error.message); + } + } + } + + /** + * 发起 PolyAPI 表单 POST 请求。 + * + * @param {object} options - 请求参数。 + * @param {string} options.method - 远端接口方法名。 + * @param {number|string} options.platid - 平台 ID。 + * @param {object|string} [options.bizcontent={}] - 业务参数内容。 + * @returns {Promise} 接口响应 data。 + */ + async request(options = {}) { + const { + method, + platid, + bizcontent = {}, + } = options; + + const config = await this.getConfig(platid); + if (!config) { + throw new Error('未找到 polyapi 配置'); + } + + const signMap = this._buildSignMap(config, method, platid, bizcontent); + const signText = this._getSignText(signMap, config.app_secret); + const sign = this._md5(signText.toLowerCase()); + const formBody = this._encodeForm({ ...signMap, sign }); + + const response = await this.ctx.curl(String(config.interface_url || ''), { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', + }, + content: formBody, + }); + + return response && response.data !== undefined ? response.data : null; + } + + // ── 内部方法 ── + + /** + * 组装签名所需的请求参数。 + */ + _buildSignMap(config, method, platid, bizcontent) { + const normalizedBizcontent = bizcontent && typeof bizcontent === 'object' + ? JSON.stringify(bizcontent) + : (bizcontent === undefined || bizcontent === null ? '' : bizcontent); + + return { + method, + appkey: config.appkey, + token: config.token, + platid, + version: config.version, + contenttype: this.contenttype, + bizcontent: normalizedBizcontent, + timestamp: this._formatDate(new Date()), + }; + } + + /** + * 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。 + */ + _getSignText(signMap, secret) { + let sb = '' + secret; + Object.keys(signMap).sort().forEach(key => { + sb += key + signMap[key]; + }); + sb += secret; + return sb; + } + + /** + * MD5 摘要。 + */ + _md5(text, encoding = 'utf8') { + return crypto.createHash('md5').update(text, encoding).digest('hex'); + } + + /** + * 将参数编码为 application/x-www-form-urlencoded。 + */ + _encodeForm(map) { + const params = new URLSearchParams(); + for (const key of Object.keys(map)) { + const v = map[key]; + params.append(key, v === undefined || v === null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v))); + } + return params.toString(); + } + + /** + * 格式化日期 → yyyy-MM-dd HH:mm:ss。 + */ + _formatDate(date) { + const pad = n => (n < 10 ? '0' + n : n); + return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); + } + + /** + * 格式化取件日期。 + */ + _formatPickupDate(year, month, day) { + const pad = n => (n < 10 ? '0' + n : n); + return `${year}-${pad(month)}-${pad(day)} 18:00:00`; + } +} + +module.exports = PoloApiClient; diff --git a/app/lib/warehouse_shard_guard.js b/app/lib/warehouse_shard_guard.js new file mode 100644 index 0000000..27313e1 --- /dev/null +++ b/app/lib/warehouse_shard_guard.js @@ -0,0 +1,93 @@ +'use strict'; + +const MAX_DECIMAL_DIGITS = 20; + +/** + * 将分表用的仓库 ID 规范为纯十进制数字串(与 wms_store.id / BIGINT 一致)。 + * @param {*} value 待规范化的仓库 ID。 + * @return {string} 规范化后的仓库 ID 字符串。 + */ +function normalizeWarehouseShardId(value) { + if (value === null || value === undefined || value === '') { + throw new Error('warehouse_id 不能为空'); + } + if (typeof value === 'object') { + throw new Error('warehouse_id 必须为数字'); + } + const s = String(value).trim(); + if (!/^\d+$/.test(s)) { + throw new Error('warehouse_id 必须为数字'); + } + if (s === '0') { + throw new Error('warehouse_id 非法'); + } + if (s.length > MAX_DECIMAL_DIGITS) { + throw new Error('warehouse_id 超出范围'); + } + return s; +} + +/** + * 校验 wms_store 中存在对应 ID 且主体为仓库(project = warehouse)。 + * @param {import('egg').Application} app 应用实例。 + * @param {string} warehouseIdStr normalizeWarehouseShardId 的返回值。 + * @return {Promise} + */ +async function assertWarehouseStoreSubject(app, warehouseIdStr) { + if (!app.model || !app.model.Store) { + return; + } + const row = await app.model.Store.findOne({ + where: { + id: warehouseIdStr, + project: 'warehouse', + }, + attributes: [ 'id' ], + paranoid: true, + }); + if (!row) { + throw new Error(`仓库主体不存在或非仓库类型(wms_store.project 须为 warehouse): ${warehouseIdStr}`); + } +} + +function validatedSetFor(app) { + if (!app._shardWarehouseIdsValidated) { + app._shardWarehouseIdsValidated = new Set(); + } + return app._shardWarehouseIdsValidated; +} + +/** + * 规范化并校验仓库分表 ID。 + * @param {import('egg').Application} app 应用实例。 + * @param {*} raw 原始仓库 ID。 + * @return {Promise} 规范化并校验后的仓库 ID 字符串。 + */ +async function ensureShardWarehouseId(app, raw) { + const idStr = normalizeWarehouseShardId(raw); + const validatedSet = validatedSetFor(app); + if (validatedSet.has(idStr)) { + return idStr; + } + await assertWarehouseStoreSubject(app, idStr); + validatedSet.add(idStr); + return idStr; +} + +/** + * 清理进程内「已校验仓库主体」缓存(例如单测或手动 clear 动态模型缓存时)。 + * @param {import('egg').Application} app 应用实例。 + * @return {void} + */ +function clearShardWarehouseValidationCache(app) { + if (app && app._shardWarehouseIdsValidated) { + app._shardWarehouseIdsValidated.clear(); + } +} + +module.exports = { + normalizeWarehouseShardId, + assertWarehouseStoreSubject, + ensureShardWarehouseId, + clearShardWarehouseValidationCache, +}; diff --git a/app/model/express_platform.js b/app/model/express_platform.js new file mode 100644 index 0000000..b7088e8 --- /dev/null +++ b/app/model/express_platform.js @@ -0,0 +1,75 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, STRING } = app.Sequelize; + + const ExpressPlatform = app.model.define('express_platform', { + id: { + type: INTEGER(10), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '接口ID', + }, + interface_url: { + type: STRING(500), + allowNull: false, + comment: '外部接口URL', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台代码,用于应用分流', + }, + interface_name: { + type: STRING(200), + allowNull: false, + comment: '接口名称', + }, + interface_url_jd: { + type: STRING(500), + allowNull: true, + comment: '京东接口URL', + }, + appkey: { + type: STRING(100), + allowNull: true, + comment: '应用Key', + }, + app_secret: { + type: STRING(255), + allowNull: true, + field: 'AppSecret', + comment: '应用密钥', + }, + token: { + type: STRING(255), + allowNull: true, + comment: '访问令牌', + }, + version: { + type: STRING(20), + allowNull: true, + comment: '接口版本', + }, + }, { + tableName: 'wms_express_interface', + freezeTableName: true, + underscored: true, + timestamps: false, + paranoid: false, + comment: '快递外部接口配置表', + indexes: [ + { + name: 'idx_platform_code', + fields: [ 'platform_code' ], + }, + { + name: 'idx_interface_name', + fields: [ 'interface_name' ], + }, + ], + }); + + return ExpressPlatform; +}; \ No newline at end of file diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index aff14fe..5bf310e 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -39,6 +39,7 @@ module.exports = app => { Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }), Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }), Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), + Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), Object.freeze({ code: 'store_warehouse_print_quantity_adjusted', name: '货主面单余额调整', @@ -229,7 +230,11 @@ module.exports = app => { }); const subjectConfig = app.model.Store && typeof app.model.Store.normalizeSubjectConfig === 'function' ? app.model.Store.normalizeSubjectConfig(store && store.subject_config) - : { max_notice_webhook_count: 5 }; + : { + max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', + }; const maxWebhookCount = Number(subjectConfig.max_notice_webhook_count || 5); const where = { diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 586c61c..56fb99a 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -15,7 +15,7 @@ module.exports = app => { INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ], PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ], CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ], - OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'error' ], + OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'timeout', 'error' ], LOCK_STATUS: [ 'none', 'warehouse', 'store' ], INTERCEPT_STATUS: [ 'none', 'requesting', 'requested', 'intercepting', @@ -74,6 +74,16 @@ module.exports = app => { allowNull: true, comment: '来源平台名称', }, + sys_platform_code: { + type: STRING(50), + allowNull: true, + comment: '系统平台编码', + }, + sys_platform_name: { + type: STRING(200), + allowNull: true, + comment: '系统平台名称', + }, create_at: { type: DATE, allowNull: true, @@ -184,6 +194,16 @@ module.exports = app => { allowNull: true, comment: '物流公司名称', }, + sys_logistics_code: { + type: STRING(50), + allowNull: true, + comment: '系统物流公司编码', + }, + sys_logistics_name: { + type: STRING(200), + allowNull: true, + comment: '系统物流公司名称', + }, express_code: { type: STRING(50), allowNull: true, @@ -389,7 +409,7 @@ module.exports = app => { print_status: { type: ENUM(...StatusEnum.PRINT_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '打印状态机', }, claim_status: { @@ -407,13 +427,13 @@ module.exports = app => { lock_status: { type: ENUM(...StatusEnum.LOCK_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '锁定状态机', }, intercept_status: { type: ENUM(...StatusEnum.INTERCEPT_STATUS), allowNull: true, - defaultValue: null, + defaultValue: 'none', comment: '拦截状态机', }, }; @@ -439,8 +459,7 @@ module.exports = app => { }, { name: 'idx_items', - fields: [ 'items' ], - length: 50, + fields: [{ attribute: 'items', length: 50 }], }, { name: 'idx_items_hash', diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index da70625..0127ed4 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -1,6 +1,109 @@ // app/model/wms_order_delivery_factory.js 'use strict'; +const { + ensureShardWarehouseId, + clearShardWarehouseValidationCache, +} = require('../lib/warehouse_shard_guard'); +const { + normalizeManagedType, + isOutsourcedType, + normalizeIndexDefinition, + parseNumericConstraint, + buildTableAttributes, + buildTableName: buildManagedTableName, + buildTableComment, + buildTableOptions, + buildIndexOptions, + buildColumnLines, + buildIndexLines, + parseManagedTableName, +} = require('./order_delivery_table_schema'); + +const LANES = Object.freeze({ + M4: 'm4', + M5: 'm5', +}); + +/** + * 判断两个索引定义是否存在结构差异。 + * @param {Object} expectedIndex 预期索引定义。 + * @param {Object} actualIndex 实际索引定义。 + * @return {boolean} 是否存在结构差异。 + */ +function isIndexDefinitionDifferent(expectedIndex, actualIndex) { + const normalizedExpected = normalizeIndexDefinition(expectedIndex); + const normalizedActual = normalizeIndexDefinition(actualIndex); + + if (!normalizedActual.name) { + return true; + } + + const actualUniqueDefined = Object.prototype.hasOwnProperty.call(actualIndex || {}, 'unique') + || Object.prototype.hasOwnProperty.call(actualIndex || {}, 'Unique') + || Object.prototype.hasOwnProperty.call(actualIndex || {}, 'nonUnique'); + + if (actualUniqueDefined && normalizedExpected.unique !== normalizedActual.unique) { + return true; + } + + if (!Array.isArray(actualIndex && actualIndex.fields) || !actualIndex.fields.length) { + return false; + } + + if (normalizedExpected.fields.length !== normalizedActual.fields.length) { + return true; + } + + for (let index = 0; index < normalizedExpected.fields.length; index += 1) { + const expectedField = normalizedExpected.fields[index]; + const actualField = normalizedActual.fields[index]; + + if (!expectedField.attribute || !actualField.attribute) { + return true; + } + + if (expectedField.attribute !== actualField.attribute) { + return true; + } + + if (Object.prototype.hasOwnProperty.call(expectedField, 'length') && expectedField.length !== actualField.length) { + return true; + } + } + + return false; +} + +/** + * 转义 SQL 标识符。 + * @param {string} identifier 标识符。 + * @return {string} 转义后的标识符。 + */ +function quoteIdentifier(identifier) { + return `\`${String(identifier).replace(/`/g, '``')}\``; +} + +/** + * 构造表数据约束违规错误。 + * @param {string} tableName 表名。 + * @param {string} columnName 列名。 + * @param {string} violationType 违规类型。 + * @param {string} [detail] 违规详情。 + * @return {Error} 错误对象。 + */ +function buildManagedTableConstraintError(tableName, columnName, violationType, detail = '') { + const suffix = detail ? `, detail=${detail}` : ''; + const error = new Error(`数据不满足约束: table=${tableName}, column=${columnName}, violation=${violationType}${suffix}`); + + error.code = 'ORDER_DELIVERY_TABLE_CONSTRAINT_VIOLATION'; + error.tableName = tableName; + error.columnName = columnName; + error.violationType = violationType; + + return error; +} + module.exports = app => { class OrderDeliveryFactory { @@ -9,6 +112,36 @@ module.exports = app => { this.app = app; } + /** + * 获取配送域车道常量。 + * @return {Object} 车道常量。 + */ + get LANES() { + return LANES; + } + + /** + * 判断是否为配送域模型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为配送域模型。 + */ + isDispatchType(type) { + return type === 'dispatch'; + } + + /** + * 解析模型类型。 + * @param {string} type 模型类型。 + * @return {string} 解析后的模型类型。 + */ + resolveModelType(type) { + return normalizeManagedType(type); + } + + isOutsourcedModel(type) { + return isOutsourcedType(type); + } + /** * 获取当前表模型 * @param {number} warehouseId 仓库ID @@ -27,6 +160,37 @@ module.exports = app => { return await this.getOrCreateModel(warehouseId, 'history'); } + /** + * 获取配送域模型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域模型。 + */ + async getDispatchModel(warehouseId) { + return await this.getOrCreateModel(warehouseId, 'dispatch'); + } + + async getOutsourcedModel(warehouseId) { + return await this.getOrCreateModel(warehouseId, 'outsourced'); + } + + /** + * 获取配送正常模型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域模型。 + */ + async getM4Model(warehouseId) { + return await this.getDispatchModel(warehouseId); + } + + /** + * 获取配送异常模型。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域模型。 + */ + async getM5Model(warehouseId) { + return await this.getDispatchModel(warehouseId); + } + /** * 根据表名直接获取模型 * @param {string} tableName 表名 @@ -40,17 +204,18 @@ module.exports = app => { } try { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + throw new Error(`表 ${tableName} 不是订单工厂管理表`); + } + const tableExists = await this.checkTableExists(tableName); if (!tableExists) { throw new Error(`表 ${tableName} 不存在`); } - const baseAttributes = this.app.model.OrderDelivery.rawAttributes; - const DynamicModel = this.app.model.define(tableName, baseAttributes, { - tableName, - timestamps: false, - comment: tableName.includes('_history') ? '仓库发货单历史表' : '仓库发货单常用表', - }); + const DynamicModel = this.buildManagedModel(parsed.warehouseId, parsed.type, tableName); + await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId, DynamicModel); this.modelCache.set(cacheKey, DynamicModel); return DynamicModel; @@ -67,9 +232,11 @@ module.exports = app => { * @param {string} type 模型类型 * @return {Promise} 动态模型 */ - async getOrCreateModel(warehouseId, type = 'current') { - const tableName = this.generateTableName(warehouseId, type); - const cacheKey = `${warehouseId}_${type}`; + async getOrCreateModel(warehouseId, type) { + const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId); + const modelType = this.resolveModelType(type); + const tableName = this.generateTableName(warehouseIdStr, modelType); + const cacheKey = `${warehouseIdStr}_${modelType}`; // 检查缓存 if (this.modelCache.has(cacheKey)) { @@ -77,20 +244,12 @@ module.exports = app => { } try { - // 检查表是否存在,不存在则创建 - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - await this.createPhysicalTable(warehouseId, type); - } + const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName); - // 创建模型实例 - const baseAttributes = this.app.model.OrderDelivery.rawAttributes; - const modelOptions = this.getModelOptions(tableName, warehouseId, type); - - const DynamicModel = this.app.model.define(tableName, baseAttributes, modelOptions); + await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel); // 设置关联关系 - this.setupAssociations(DynamicModel, warehouseId, type); + this.setupAssociations(DynamicModel, warehouseIdStr, modelType); // 缓存模型 this.modelCache.set(cacheKey, DynamicModel); @@ -106,28 +265,36 @@ module.exports = app => { /** * 获取模型配置选项 - * @param {string} tableName 表名 * @param {number} warehouseId 仓库ID * @param {string} type 模型类型 * @return {Object} Sequelize 模型配置 */ - getModelOptions(tableName, warehouseId, type) { - const options = { - tableName, - timestamps: false, - comment: type === 'history' - ? `仓库${warehouseId}发货单历史表` - : `仓库${warehouseId}发货单常用表`, - indexes: this.getIndexes(warehouseId, type), - }; + getModelOptions(warehouseId, type) { + return buildTableOptions(this.app, warehouseId, type); + } - // 历史表添加归档时间字段 - if (type === 'history') { - options.fields = Object.keys(this.app.model.OrderDelivery.rawAttributes); - options.fields.push('archive_time'); - } + /** + * 构建动态模型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @param {string} tableName 表名。 + * @return {Object} 动态模型。 + */ + buildManagedModel(warehouseId, type, tableName) { + const modelType = this.resolveModelType(type); + const attributes = this.getTableAttributes(modelType); + const modelOptions = this.getModelOptions(warehouseId, modelType); - return options; + return this.app.model.define(tableName, attributes, modelOptions); + } + + /** + * 获取订单工厂管理的属性定义。 + * @param {string} type 模型类型。 + * @return {Object} 属性定义。 + */ + getTableAttributes(type) { + return buildTableAttributes(this.app, type); } /** @@ -137,63 +304,89 @@ module.exports = app => { * @return {Array} 索引配置 */ getIndexes(warehouseId, type) { - const prefix = `${warehouseId}_${type}`; + return buildIndexOptions(warehouseId, type); + } - return [ - { - name: `idx_${prefix}_store_id`, - fields: [ 'store_id' ], - }, - { - name: `idx_${prefix}_warehouse_id`, - fields: [ 'warehouse_id' ], - }, - { - name: `idx_${prefix}_delivery_code`, - unique: true, - fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ], - }, - { - name: `idx_${prefix}_items`, - fields: [ 'items' ], - length: 50, - }, - { - name: `idx_${prefix}_items_hash`, - fields: [ 'items_hash' ], - }, - { - name: `idx_${prefix}_hash_crc`, - fields: [ 'items_hash', 'items_crc', 'warehouse_id' ], - }, - { - name: `idx_${prefix}_wave`, - fields: [ 'status', 'wave_id' ], - }, - { - name: `idx_${prefix}_statuses`, - fields: [ - 'status', - 'post_status', - 'pick_status', - 'pack_status', - 'outbound_status', - ], - }, - ]; + /** + * 获取当前表通用列定义行。 + * + * @param {string} type 模型类型 + * @return {Array} 当前表列定义行 + */ + getCurrentTableColumnLines(type = 'current') { + return buildColumnLines(this.app, type); + } + + /** + * 获取当前表通用索引定义行。 + * + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Array} 当前表索引定义行 + */ + getCurrentTableIndexLines(warehouseId, type = 'current') { + return buildIndexLines(warehouseId, type); + } + + /** + * 获取配送域物理表名。 + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 配送域物理表名。 + */ + async getDispatchTableName(warehouseId) { + const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId); + return `wms_order_delivery_dispatch_${warehouseIdStr}`; + } + + /** + * 获取配送域表列定义行。 + * @return {Array} 配送域表列定义行。 + */ + getDispatchTableColumnLines() { + return buildColumnLines(this.app, 'dispatch'); + } + + /** + * 获取配送域表索引定义行。 + * @param {string} warehouseIdStr 仓库ID字符串。 + * @return {Array} 配送域表索引定义行。 + */ + getDispatchTableIndexLines(warehouseIdStr) { + return buildIndexLines(warehouseIdStr, 'dispatch'); + } + + /** + * 获取配送域索引配置。 + * @param {string} warehouseIdStr 仓库ID字符串。 + * @return {Array} Sequelize 索引配置。 + */ + getDispatchTableIndexOptions(warehouseIdStr) { + return buildIndexOptions(warehouseIdStr, 'dispatch'); + } + + /** + * 获取配送域属性定义。 + * @return {Object} 配送域属性定义。 + */ + getDispatchAttributes() { + return this.getTableAttributes('dispatch'); + } + + buildDispatchAttributes() { + return this.getDispatchAttributes(); } /** * 设置关联关系 - * @param {Object} DynamicModel 动态模型 - * @param {number} warehouseId 仓库ID - * @param {string} type 模型类型 - * @return {Promise} + * @param {Object} DynamicModel 动态模型 + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} */ async setupAssociations(DynamicModel, warehouseId, type) { try { - // 如果存在商品模型工厂,建立关联 - if (this.app.model.OrderItemsFactory) { + // 配送域不挂商品明细关联,其余模式保持原行为。 + if (!this.isDispatchType(type) && this.app.model.OrderItemsFactory) { const ItemsModel = await this.app.model.OrderItemsFactory.getOrCreateModel(warehouseId, type); // 发货单 -> 商品 (1:N) @@ -237,8 +430,8 @@ module.exports = app => { /** * 检查表是否存在 - * @param {string} tableName 表名 - * @return {Promise} 是否存在 + * @param {string} tableName 表名 + * @return {Promise} 是否存在 */ async checkTableExists(tableName) { const sequelize = this.app.model; @@ -263,113 +456,233 @@ module.exports = app => { } } + /** + * 判断目标表是否需要进行结构同步。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {boolean|null} [tableExists=null] 是否已确认表存在。 + * @return {Promise} 是否需要同步。 + */ + async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) { + const queryInterface = this.app.model.getQueryInterface(); + const managedTableExists = typeof tableExists === 'boolean' + ? tableExists + : await this.checkTableExists(tableName); + + if (!managedTableExists) { + return true; + } + + const [ tables, indexes ] = await Promise.all([ + queryInterface.describeTable(tableName), + typeof queryInterface.showIndex === 'function' + ? queryInterface.showIndex(tableName) + : Promise.resolve([]), + ]); + + const expectedAttributes = this.getTableAttributes(type); + const expectedAttributeNames = Object.keys(expectedAttributes); + const actualAttributeNames = Object.keys(tables || {}); + + if (expectedAttributeNames.length !== actualAttributeNames.length) { + return true; + } + + const actualColumnNames = new Set(actualAttributeNames); + + for (const columnName of expectedAttributeNames) { + if (!actualColumnNames.has(columnName)) { + return true; + } + } + + for (const columnName of expectedAttributeNames) { + const expectedColumn = expectedAttributes[columnName]; + const actualColumn = tables[columnName] || {}; + const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function' + ? expectedColumn.type.toSql().toLowerCase() + : String(expectedColumn.type || '').toLowerCase(); + const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase(); + const expectedAllowNull = expectedColumn.allowNull !== false; + const actualAllowNull = actualColumn.allowNull !== false; + const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue') + ? expectedColumn.defaultValue + : undefined; + const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue') + ? actualColumn.defaultValue + : undefined; + + if (expectedType && actualType && expectedType !== actualType) { + return true; + } + + if (expectedAllowNull !== actualAllowNull) { + return true; + } + + const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault); + const normalizedActualDefault = actualDefault == null ? null : String(actualDefault); + if (normalizedExpectedDefault !== normalizedActualDefault) { + return true; + } + } + + const expectedIndexes = this.getIndexes(warehouseId, type); + const actualIndexes = Array.isArray(indexes) ? indexes : []; + + for (const expectedIndex of expectedIndexes) { + const actualIndex = actualIndexes.find(index => (index.Key_name || index.name) === expectedIndex.name); + + if (!actualIndex) { + return true; + } + + if (isIndexDefinitionDifferent(expectedIndex, actualIndex)) { + return true; + } + } + + return false; + } + + /** + * 在结构同步前预检现有数据是否满足非空和数值范围约束。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @return {Promise} + */ + async assertManagedTableDataConstraints(tableName, type) { + const queryInterface = this.app.model.getQueryInterface(); + const sequelize = this.app.model; + const tableColumns = await queryInterface.describeTable(tableName); + const expectedAttributes = this.getTableAttributes(type); + const columnNames = new Set(Object.keys(tableColumns || {})); + + for (const columnName of Object.keys(expectedAttributes)) { + if (!columnNames.has(columnName)) { + continue; + } + + const expectedAttribute = expectedAttributes[columnName]; + const quotedTableName = quoteIdentifier(tableName); + const quotedColumnName = quoteIdentifier(columnName); + + if (expectedAttribute.allowNull === false) { + const [ nullRows ] = await sequelize.query( + `SELECT 1 AS violationFound FROM ${quotedTableName} WHERE ${quotedColumnName} IS NULL LIMIT 1` + ); + + if (Array.isArray(nullRows) && nullRows.length > 0) { + throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL'); + } + } + + const numericConstraint = parseNumericConstraint(expectedAttribute); + + if (!numericConstraint) { + continue; + } + + const [ rangeRows ] = await sequelize.query( + `SELECT 1 AS violationFound FROM ${quotedTableName} + WHERE ${quotedColumnName} IS NOT NULL + AND (${quotedColumnName} < :minValue OR ${quotedColumnName} > :maxValue) + LIMIT 1`, + { + replacements: { + minValue: numericConstraint.min, + maxValue: numericConstraint.max, + }, + } + ); + + if (Array.isArray(rangeRows) && rangeRows.length > 0) { + throw buildManagedTableConstraintError( + tableName, + columnName, + 'NUMERIC_RANGE', + `expected=[${numericConstraint.min}, ${numericConstraint.max}]` + ); + } + } + } + + /** + * 确保单个目标表与模型结构一致。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [DynamicModel] 已构建的动态模型。 + * @return {Promise} 是否执行了同步。 + */ + async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) { + const modelType = this.resolveModelType(type); + const dynamicModel = DynamicModel || this.buildManagedModel(warehouseId, modelType, tableName); + const tableExists = await this.checkTableExists(tableName); + const needsSync = tableExists + ? await this.needsTableSchemaSync(tableName, modelType, warehouseId, tableExists) + : true; + + if (!needsSync) { + return false; + } + + if (tableExists) { + await this.assertManagedTableDataConstraints(tableName, modelType); + } + + await dynamicModel.sync({ alter: true }); + return true; + } + + /** + * 扫描并同步订单工厂管理的目标表。 + * @return {Promise} + */ + async ensureManagedTableSchemas() { + const tableNames = await this.listManagedTableNames(); + + for (const tableName of tableNames) { + const parsed = parseManagedTableName(tableName); + if (!parsed) { + continue; + } + + await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId); + } + } + + /** + * 获取当前库中已存在的订单工厂目标表。 + * @return {Promise>} 目标表名列表。 + */ + async listManagedTableNames() { + const [ rows ] = await this.app.model.query(` + SELECT TABLE_NAME AS tableName + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME LIKE 'wms_order_delivery_%' + `); + + return rows + .map(item => item.tableName) + .filter(tableName => parseManagedTableName(tableName)); + } + /** * 创建物理表 * @param {number} warehouseId 仓库ID * @param {string} type 模型类型 * @return {Promise} */ - async createPhysicalTable(warehouseId, type = 'current') { - const tableName = this.generateTableName(warehouseId, type); - const tableComment = type === 'history' - ? `仓库${warehouseId}发货单历史表` - : `仓库${warehouseId}发货单常用表`; + async createPhysicalTable(warehouseId, type) { + const modelType = this.resolveModelType(type); + const tableName = this.generateTableName(warehouseId, modelType); + const dynamicModel = this.buildManagedModel(warehouseId, modelType, tableName); - // 添加历史表特有的字段 - const historyFields = type === 'history' ? - ',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; - - const createTableSQL = ` - CREATE TABLE \`${tableName}\` ( - \`id\` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, - \`delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '发货单号', - \`pre_delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '预发货单号', - \`pre_delivery_order_id\` varchar(50) DEFAULT NULL COMMENT '预发货单ID', - \`order_type\` varchar(50) DEFAULT NULL COMMENT '订单类型', - \`warehouse_code\` varchar(50) DEFAULT NULL COMMENT '仓库编码', - \`order_flag\` varchar(200) DEFAULT NULL COMMENT '订单标记', - \`source_platform_code\` varchar(50) DEFAULT NULL COMMENT '来源平台编码', - \`source_platform_name\` varchar(200) DEFAULT NULL COMMENT '来源平台名称', - \`create_at\` datetime DEFAULT NULL COMMENT '创建时间', - \`delete_at\` datetime DEFAULT NULL COMMENT '删除时间', - \`updated_at\` datetime DEFAULT NULL COMMENT '更新时间', - \`place_order_time\` datetime DEFAULT NULL COMMENT '店铺创建订单时间', - \`pay_time\` datetime DEFAULT NULL COMMENT '支付时间', - \`pay_no\` varchar(50) DEFAULT NULL COMMENT '支付单号', - \`service_code\` varchar(50) DEFAULT NULL COMMENT '集包服务编码', - \`operator_name\` varchar(50) DEFAULT NULL COMMENT 'ERP审核人', - \`operate_time\` datetime DEFAULT NULL COMMENT 'ERP审核时间', - \`delivery_time\` datetime DEFAULT NULL COMMENT '发货时间', - \`shop_nick\` varchar(200) DEFAULT NULL COMMENT '店铺名称', - \`seller_nick\` varchar(200) DEFAULT NULL COMMENT '卖家名称', - \`buyer_nick\` varchar(200) DEFAULT NULL COMMENT '买家名称', - \`total_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单总金额', - \`item_amount\` decimal(18,2) DEFAULT NULL COMMENT '商品总金额', - \`discount_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单折扣金额', - \`freight\` decimal(18,2) DEFAULT NULL COMMENT '快递费用', - \`ar_amount\` decimal(18,2) DEFAULT NULL COMMENT '应收金额', - \`got_amount\` decimal(18,2) DEFAULT NULL COMMENT '已收金额', - \`service_fee\` decimal(18,2) DEFAULT NULL COMMENT 'COD服务费', - \`logistics_code\` varchar(50) DEFAULT NULL COMMENT '物流公司编码', - \`logistics_name\` varchar(200) DEFAULT NULL COMMENT '物流公司名称', - \`express_code\` varchar(50) DEFAULT NULL COMMENT '面单号前置', - \`logistics_area_code\` varchar(50) DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', - \`delivery_type\` varchar(255) DEFAULT NULL COMMENT '发货服务类型', - \`is_urgency\` enum('Y','N') DEFAULT 'N' COMMENT '是否紧急', - \`invoice_flag\` enum('Y','N') DEFAULT 'N' COMMENT '是否需要发票', - \`status\` enum('pedding','created','cancel','error') DEFAULT 'created' COMMENT '状态', - \`name\` text COMMENT '收件人姓名', - \`zip_code\` varchar(50) DEFAULT NULL COMMENT '收件人邮编', - \`tel\` text COMMENT '收件人电话', - \`mobile\` text COMMENT '收件人移动电话', - \`email\` text COMMENT '收件人邮箱', - \`country_code\` varchar(255) DEFAULT NULL COMMENT '国家编码', - \`province\` varchar(255) DEFAULT NULL COMMENT '省份', - \`city\` varchar(255) DEFAULT NULL COMMENT '城市', - \`area\` varchar(255) DEFAULT NULL COMMENT '区', - \`town\` varchar(255) DEFAULT NULL COMMENT '镇', - \`detail_address\` varchar(255) DEFAULT NULL COMMENT '详细地址', - \`id_type\` varchar(255) DEFAULT NULL COMMENT '证件类型', - \`id_number\` int(11) DEFAULT NULL COMMENT '证件号码', - \`oaid\` text COMMENT 'OAID', - \`sync_status\` enum('padding','fin','error') DEFAULT 'padding' COMMENT '同步状态', - \`store_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '货主id', - \`warehouse_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '仓库id', - \`from_key\` int(11) DEFAULT NULL COMMENT '来源键', - \`items\` text COMMENT '商品结构字符串', - \`items_count\` smallint(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品种类数', - \`items_total\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品总数', - \`items_weight\` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '总重量', - \`items_hash\` char(32) NOT NULL DEFAULT '' COMMENT '哈希值', - \`items_crc\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '校验码', - \`wave_id\` bigint(20) NOT NULL DEFAULT '0' COMMENT '波次ID,0表示未分配', - \`post_status\` enum('padding','fin','timeout','error','none') DEFAULT 'none' COMMENT '分配快递号状态机', - \`storage_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '分配储位状态机', - \`pick_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '拣货状态机', - \`pack_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '打包状态机', - \`inspection_status\` enum('none','padding','running','fin','error') DEFAULT 'none' COMMENT '检验状态机', - \`step\` int(10) NOT NULL DEFAULT '0' COMMENT '订单步骤:0未审核,1已审核', - \`print_status\` enum('none','padding','fin','error') DEFAULT NULL COMMENT '打印状态机', - \`claim_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '领取状态机', - \`outbound_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '出库状态机', - \`lock_status\` enum('none','warehouse','store') DEFAULT NULL COMMENT '锁定状态机', - \`intercept_status\` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') DEFAULT NULL COMMENT '拦截状态机' - ${historyFields}, - PRIMARY KEY (\`id\`), - UNIQUE KEY \`idx_${warehouseId}_${type}_delivery_code\` (\`delivery_order_code\`,\`store_id\`,\`warehouse_id\`), - KEY \`idx_${warehouseId}_${type}_store_id\` (\`store_id\`), - KEY \`idx_${warehouseId}_${type}_warehouse_id\` (\`warehouse_id\`), - KEY \`idx_${warehouseId}_${type}_items\` (\`items\`(50)), - KEY \`idx_${warehouseId}_${type}_items_hash\` (\`items_hash\`), - KEY \`idx_${warehouseId}_${type}_hash_crc\` (\`items_hash\`,\`items_crc\`,\`warehouse_id\`), - KEY \`idx_${warehouseId}_${type}_wave\` (\`status\`,\`wave_id\`), - KEY \`idx_${warehouseId}_${type}_statuses\` (\`status\`,\`post_status\`,\`pick_status\`,\`pack_status\`,\`outbound_status\`) - ${type === 'history' ? `,KEY \`idx_${warehouseId}_history_archive_time\` (\`archive_time\`)` : ''} - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='${tableComment}'; - `; - - await this.app.model.query(createTableSQL); - this.app.logger.info(`创建物理表成功: ${tableName}`); + await dynamicModel.sync({ alter: true }); + this.app.logger.info(`创建/同步物理表成功: ${tableName}`); } /** @@ -387,7 +700,7 @@ module.exports = app => { step: [ 0, 1 ], print_status: [ 'none', 'padding', 'fin', 'error' ], claim_status: [ 'none', 'padding', 'fin', 'error' ], - outbound_status: [ 'none', 'padding', 'fin', 'error' ], + outbound_status: [ 'none', 'padding', 'fin', 'timeout', 'error' ], lock_status: [ 'none', 'warehouse', 'store' ], intercept_status: [ 'none', 'requesting', 'requested', 'intercepting', @@ -405,8 +718,18 @@ module.exports = app => { * @return {string} 表名 */ generateTableName(warehouseId, type) { - const suffix = type === 'history' ? '_history' : ''; - return `wms_order_delivery_${warehouseId}${suffix}`; + const modelType = this.resolveModelType(type); + return buildManagedTableName(warehouseId, modelType); + } + + /** + * 获取订单工厂管理表的注释。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {string} 表注释。 + */ + getTableComment(warehouseId, type) { + return buildTableComment(warehouseId, type); } /** @@ -414,6 +737,7 @@ module.exports = app => { */ clearCache() { this.modelCache.clear(); + clearShardWarehouseValidationCache(this.app); this.app.logger.info('模型缓存已清理'); } diff --git a/app/model/order_delivery_table_schema.js b/app/model/order_delivery_table_schema.js new file mode 100644 index 0000000..0e413f7 --- /dev/null +++ b/app/model/order_delivery_table_schema.js @@ -0,0 +1,521 @@ +'use strict'; + +const MANAGED_TYPES = Object.freeze({ + CURRENT: 'current', + HISTORY: 'history', + DISPATCH: 'dispatch', + OUTSOURCED: 'outsourced', +}); + +const TABLE_PATTERNS = Object.freeze([ + { + type: MANAGED_TYPES.DISPATCH, + pattern: /^wms_order_delivery_dispatch_(\d+)$/, + }, + { + type: MANAGED_TYPES.HISTORY, + pattern: /^wms_order_delivery_(\d+)_history$/, + }, + { + type: MANAGED_TYPES.OUTSOURCED, + pattern: /^wms_order_delivery_(\d+)_outsourced$/, + }, + { + type: MANAGED_TYPES.CURRENT, + pattern: /^wms_order_delivery_(\d+)$/, + }, +]); + +/** + * 规范化订单工厂管理的模型类型。 + * @param {string} type 模型类型。 + * @return {string} 规范化后的模型类型。 + */ +function normalizeManagedType(type) { + return Object.values(MANAGED_TYPES).includes(type) ? type : MANAGED_TYPES.CURRENT; +} + +/** + * 判断是否为配送域类型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为配送域类型。 + */ +function isDispatchType(type) { + return normalizeManagedType(type) === MANAGED_TYPES.DISPATCH; +} + +/** + * 判断是否为历史类型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为历史类型。 + */ +function isHistoryType(type) { + return normalizeManagedType(type) === MANAGED_TYPES.HISTORY; +} + +/** + * 判断是否为 outsourced 类型。 + * @param {string} type 模型类型。 + * @return {boolean} 是否为 outsourced 类型。 + */ +function isOutsourcedType(type) { + return normalizeManagedType(type) === MANAGED_TYPES.OUTSOURCED; +} + +/** + * 克隆模型属性定义,避免直接修改基础模型对象。 + * @param {Object} attributes 原始属性定义。 + * @return {Object} 克隆后的属性定义。 + */ +function cloneAttributes(attributes) { + return Object.entries(attributes).reduce((result, [ name, attribute ]) => { + result[name] = { ...attribute }; + return result; + }, {}); +} + +/** + * 规范化索引字段定义。 + * @param {string|Object} field 字段定义。 + * @return {{ attribute: string, length?: number }} 规范化后的字段定义。 + */ +function normalizeIndexField(field) { + if (typeof field === 'string') { + return { attribute: field }; + } + + if (!field || typeof field !== 'object') { + return { attribute: String(field) }; + } + + const attribute = field.attribute || field.name || field.field || field.columnName || field.column_name; + const normalizedField = { + attribute: attribute ? String(attribute) : '', + }; + + if (Object.prototype.hasOwnProperty.call(field, 'length') && field.length !== undefined && field.length !== null) { + normalizedField.length = Number(field.length); + } + + return normalizedField; +} + +/** + * 规范化索引定义。 + * @param {Object} index 索引定义。 + * @return {{ name: string, unique: boolean, fields: Array }} 规范化后的索引定义。 + */ +function normalizeIndexDefinition(index) { + return { + name: index.name || index.Key_name || index.key_name || '', + unique: Boolean(index.unique || index.Unique || (typeof index.nonUnique === 'number' ? index.nonUnique === 0 : false)), + fields: Array.isArray(index.fields) ? index.fields.map(normalizeIndexField) : [], + }; +} + +/** + * 规范化 Sequelize 数值类型的 SQL 定义。 + * @param {Object} attribute Sequelize 属性定义。 + * @return {{ type: string, unsigned: boolean, min: string, max: string, precision?: number, scale?: number }|null} 数值约束信息。 + */ +function parseNumericConstraint(attribute) { + let typeSql = ''; + + if (attribute && attribute.type && typeof attribute.type.toSql === 'function') { + try { + typeSql = attribute.type.toSql(); + } catch (error) { + return null; + } + } else { + typeSql = String(attribute && attribute.type || ''); + } + const normalizedTypeSql = String(typeSql || '') + .trim() + .replace(/\s+/g, ' ') + .toUpperCase(); + + if (!normalizedTypeSql) { + return null; + } + + const integerMatch = normalizedTypeSql.match(/^(TINYINT|SMALLINT|MEDIUMINT|INT|INTEGER|BIGINT)\s*(?:\(\s*\d+\s*\))?(?:\s+UNSIGNED)?$/i); + + if (integerMatch) { + const integerBits = { + TINYINT: 8, + SMALLINT: 16, + MEDIUMINT: 24, + INT: 32, + INTEGER: 32, + BIGINT: 64, + }[integerMatch[1].toUpperCase()]; + const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql); + const bigBits = BigInt(integerBits); + const max = unsigned + ? (2n ** bigBits) - 1n + : (2n ** (bigBits - 1n)) - 1n; + const min = unsigned + ? 0n + : -(2n ** (bigBits - 1n)); + + return { + type: integerMatch[1].toUpperCase(), + unsigned, + min: min.toString(), + max: max.toString(), + }; + } + + const decimalMatch = normalizedTypeSql.match(/^(DECIMAL|NUMERIC)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)(?:\s+UNSIGNED)?$/i); + + if (decimalMatch) { + const precision = Number(decimalMatch[2]); + const scale = Number(decimalMatch[3]); + const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql); + const integerDigits = precision - scale; + + if (!Number.isInteger(precision) || !Number.isInteger(scale) || precision <= 0 || scale < 0 || integerDigits <= 0) { + return null; + } + + const integerPart = '9'.repeat(integerDigits); + const decimalPart = scale > 0 ? `.${'9'.repeat(scale)}` : ''; + + return { + type: decimalMatch[1].toUpperCase(), + unsigned, + precision, + scale, + min: `-${integerPart}${decimalPart}`, + max: `${integerPart}${decimalPart}`, + }; + } + + return null; +} + +/** + * 生成默认值 SQL 片段。 + * @param {*} defaultValue 默认值。 + * @return {string} SQL 片段。 + */ +function formatDefaultValue(defaultValue) { + if (defaultValue === null) { + return 'NULL'; + } + + if (defaultValue === undefined) { + return ''; + } + + if (defaultValue && typeof defaultValue.toSql === 'function') { + return defaultValue.toSql(); + } + + if (typeof defaultValue === 'string') { + const escaped = defaultValue.replace(/'/g, "''"); + return `'${escaped}'`; + } + + if (typeof defaultValue === 'number' || typeof defaultValue === 'bigint') { + return String(defaultValue); + } + + if (typeof defaultValue === 'boolean') { + return defaultValue ? '1' : '0'; + } + + return `'${String(defaultValue).replace(/'/g, "''")}'`; +} + +/** + * 将 Sequelize 属性定义转换为 DDL 列片段。 + * @param {string} columnName 列名。 + * @param {Object} attribute Sequelize 属性定义。 + * @return {string} DDL 列片段。 + */ +function buildColumnLine(columnName, attribute) { + const parts = [ `\`${columnName}\``, attribute.type && typeof attribute.type.toSql === 'function' + ? attribute.type.toSql() + : String(attribute.type || ''), + ]; + + if (attribute.allowNull === false) { + parts.push('NOT NULL'); + } + + if (attribute.autoIncrement) { + parts.push('AUTO_INCREMENT'); + } + + if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) { + const defaultSql = formatDefaultValue(attribute.defaultValue); + if (defaultSql) { + parts.push(`DEFAULT ${defaultSql}`); + } + } + + if (attribute.comment) { + parts.push(`COMMENT '${String(attribute.comment).replace(/'/g, "''")}'`); + } + + return parts.join(' '); +} + +/** + * 构建模型属性定义。 + * @param {Object} app Egg 应用实例。 + * @param {string} type 模型类型。 + * @return {Object} 属性定义。 + */ +function buildTableAttributes(app, type) { + const modelType = normalizeManagedType(type); + const attributes = cloneAttributes(app.model.OrderDelivery.rawAttributes); + + if (isDispatchType(modelType)) { + const { ENUM } = app.Sequelize; + attributes.dispatch_lane = { + type: ENUM('m4', 'm5'), + field: 'dispatch_lane', + allowNull: false, + defaultValue: 'm4', + comment: '配送工作台子域(M4正常/M5异常)', + }; + } + + if (isHistoryType(modelType)) { + attributes.archive_time = { + type: app.Sequelize.DATE, + field: 'archive_time', + allowNull: true, + defaultValue: null, + comment: '归档时间', + }; + } + + return attributes; +} + +/** + * 构建表名。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {string} 表名。 + */ +function buildTableName(warehouseId, type) { + const modelType = normalizeManagedType(type); + + if (isDispatchType(modelType)) { + return `wms_order_delivery_dispatch_${warehouseId}`; + } + + if (isOutsourcedType(modelType)) { + return `wms_order_delivery_${warehouseId}_outsourced`; + } + + const suffix = isHistoryType(modelType) ? '_history' : ''; + return `wms_order_delivery_${warehouseId}${suffix}`; +} + +/** + * 构建表注释。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {string} 表注释。 + */ +function buildTableComment(warehouseId, type) { + const modelType = normalizeManagedType(type); + + if (isDispatchType(modelType)) { + return `仓库${warehouseId}发货单配送域(M4/M5)影子表`; + } + + if (isHistoryType(modelType)) { + return `仓库${warehouseId}发货单历史表`; + } + + if (isOutsourcedType(modelType)) { + return `仓库${warehouseId}发货单外仓表`; + } + + return `仓库${warehouseId}发货单常用表`; +} + +/** + * 构建模型选项。 + * @param {Object} app Egg 应用实例。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {Object} Sequelize 模型选项。 + */ +function buildTableOptions(app, warehouseId, type) { + const modelType = normalizeManagedType(type); + const options = { + tableName: buildTableName(warehouseId, modelType), + timestamps: false, + comment: buildTableComment(warehouseId, modelType), + indexes: buildIndexOptions(warehouseId, modelType), + }; + + if (isHistoryType(modelType)) { + options.fields = Object.keys(buildTableAttributes(app, modelType)); + } + + return options; +} + +/** + * 构建索引选项。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {Array} 索引选项。 + */ +function buildIndexOptions(warehouseId, type) { + const modelType = normalizeManagedType(type); + const prefix = `${warehouseId}_${modelType}`; + + if (isDispatchType(modelType)) { + const baseIndexes = buildIndexOptions(warehouseId, MANAGED_TYPES.CURRENT); + const dispatchLaneIndex = { + name: `idx_dispatch_${warehouseId}_dispatch_lane`, + fields: [ 'dispatch_lane', 'status' ], + }; + + return [ + baseIndexes[0], + baseIndexes[1], + baseIndexes[2], + dispatchLaneIndex, + ...baseIndexes.slice(3), + ]; + } + + const indexes = [ + { + name: `idx_${prefix}_store_id`, + fields: [ 'store_id' ], + }, + { + name: `idx_${prefix}_warehouse_id`, + fields: [ 'warehouse_id' ], + }, + { + name: `idx_${prefix}_delivery_code`, + unique: true, + fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ], + }, + { + name: `idx_${prefix}_items`, + fields: [{ attribute: 'items', length: 50 }], + }, + { + name: `idx_${prefix}_items_hash`, + fields: [ 'items_hash' ], + }, + { + name: `idx_${prefix}_hash_crc`, + fields: [ 'items_hash', 'items_crc', 'warehouse_id' ], + }, + { + name: `idx_${prefix}_wave`, + fields: [ 'status', 'wave_id' ], + }, + { + name: `idx_${prefix}_statuses`, + fields: [ + 'status', + 'post_status', + 'pick_status', + 'pack_status', + 'outbound_status', + ], + }, + ]; + + if (isHistoryType(modelType)) { + indexes.push({ + name: `idx_${warehouseId}_history_archive_time`, + fields: [ 'archive_time' ], + }); + } + + return indexes; +} + +/** + * 将索引选项转换为 DDL 片段。 + * @param {Object} index 索引定义。 + * @return {string} DDL 索引片段。 + */ +function buildIndexLine(index) { + const fieldParts = index.fields.map(field => { + const normalizedField = normalizeIndexField(field); + const length = Object.prototype.hasOwnProperty.call(normalizedField, 'length') + ? `(${normalizedField.length})` + : ''; + + return `\`${normalizedField.attribute}\`${length}`; + }); + + const prefix = index.unique ? 'UNIQUE KEY' : 'KEY'; + return `${prefix} \`${index.name}\` (${fieldParts.join(',')})`; +} + +/** + * 构建表列定义行。 + * @param {Object} app Egg 应用实例。 + * @param {string} type 模型类型。 + * @return {Array} 列定义行。 + */ +function buildColumnLines(app, type) { + return Object.entries(buildTableAttributes(app, type)).map(([ columnName, attribute ]) => buildColumnLine(columnName, attribute)); +} + +/** + * 构建表索引定义行。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @return {Array} 索引定义行。 + */ +function buildIndexLines(warehouseId, type) { + return buildIndexOptions(warehouseId, type).map(buildIndexLine); +} + +/** + * 解析订单工厂管理的表名。 + * @param {string} tableName 表名。 + * @return {{ type: string, warehouseId: string }|null} 解析结果。 + */ +function parseManagedTableName(tableName) { + for (const item of TABLE_PATTERNS) { + const match = item.pattern.exec(tableName); + if (match) { + return { + type: item.type, + warehouseId: match[1], + }; + } + } + + return null; +} + +module.exports = { + MANAGED_TYPES, + normalizeManagedType, + isDispatchType, + isHistoryType, + isOutsourcedType, + normalizeIndexField, + normalizeIndexDefinition, + parseNumericConstraint, + buildTableAttributes, + buildTableName, + buildTableComment, + buildTableOptions, + buildIndexOptions, + buildColumnLines, + buildIndexLines, + parseManagedTableName, +}; diff --git a/app/model/order_items.js b/app/model/order_items.js index efe064b..e2a47e3 100644 --- a/app/model/order_items.js +++ b/app/model/order_items.js @@ -87,6 +87,11 @@ module.exports = app => { allowNull: true, comment: '库存ID', }, + item_snapshot: { + type: JSON, + allowNull: true, + comment: '商品快照', + }, created_at: { type: Sequelize.DATE, allowNull: false, diff --git a/app/model/order_items_factory.js b/app/model/order_items_factory.js index 3ff60f1..8387acf 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -1,6 +1,101 @@ // order_items_factory.js 'use strict'; +const { + ensureShardWarehouseId, + clearShardWarehouseValidationCache, +} = require('../lib/warehouse_shard_guard'); + +/** + * 克隆模型属性定义。 + * @param {Object} attributes 属性定义。 + * @return {Object} 克隆后的属性定义。 + */ +function cloneAttributes(attributes) { + return Object.entries(attributes || {}).reduce((result, [ key, value ]) => { + result[key] = { ...value }; + return result; + }, {}); +} + +/** + * 规范化索引定义。 + * @param {Object} index 索引定义。 + * @return {Object} 规范化后的索引定义。 + */ +function normalizeIndexDefinition(index) { + let unique = false; + + if (index && Object.prototype.hasOwnProperty.call(index, 'unique')) { + unique = Boolean(index.unique); + } else if (index && Object.prototype.hasOwnProperty.call(index, 'Unique')) { + unique = Boolean(index.Unique); + } else if (index && Object.prototype.hasOwnProperty.call(index, 'nonUnique')) { + unique = Number(index.nonUnique) === 0; + } + + return { + name: index && (index.name || index.Key_name || index.key_name || index.index_name) || '', + unique, + fields: Array.isArray(index && index.fields) + ? index.fields.map(field => { + if (typeof field === 'string') { + return { + attribute: field, + }; + } + + return { + attribute: field.attribute || field.name || field.field || field.columnName || '', + length: field.length, + }; + }) + : [], + }; +} + +/** + * 判断两个索引定义是否存在结构差异。 + * @param {Object} expectedIndex 预期索引定义。 + * @param {Object} actualIndex 实际索引定义。 + * @return {boolean} 是否存在结构差异。 + */ +function isIndexDefinitionDifferent(expectedIndex, actualIndex) { + const normalizedExpected = normalizeIndexDefinition(expectedIndex); + const normalizedActual = normalizeIndexDefinition(actualIndex); + + if (!normalizedActual.name) { + return true; + } + + if (normalizedExpected.unique !== normalizedActual.unique) { + return true; + } + + if (normalizedExpected.fields.length !== normalizedActual.fields.length) { + return true; + } + + for (let index = 0; index < normalizedExpected.fields.length; index += 1) { + const expectedField = normalizedExpected.fields[index]; + const actualField = normalizedActual.fields[index]; + + if (!expectedField.attribute || !actualField.attribute) { + return true; + } + + if (expectedField.attribute !== actualField.attribute) { + return true; + } + + if (Object.prototype.hasOwnProperty.call(expectedField, 'length') && expectedField.length !== actualField.length) { + return true; + } + } + + return false; +} + module.exports = app => { const { Sequelize } = app; @@ -29,6 +124,15 @@ module.exports = app => { return await this.getOrCreateModel(warehouseId, 'history'); } + /** + * 获取配送表模型。 + * @param {number} warehouseId 仓库ID + * @return {Promise} 配送表模型 + */ + async getDispatchModel(warehouseId) { + return await this.getOrCreateModel(warehouseId, 'dispatch'); + } + /** * 获取或创建模型 * @param {number} warehouseId 仓库ID @@ -36,14 +140,15 @@ module.exports = app => { * @return {Promise} 动态模型 */ async getOrCreateModel(warehouseId, type = 'current') { - const cacheKey = `${warehouseId}_${type}`; + const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId); + const cacheKey = `${warehouseIdStr}_${type}`; // 检查缓存 if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } - const tableName = this.generateTableName(warehouseId, type); + const tableName = this.generateTableName(warehouseIdStr, type); try { // 防止并发创建表 @@ -52,7 +157,7 @@ module.exports = app => { return this.modelCache.get(cacheKey); } - const createPromise = this.createModelWithRetry(warehouseId, type, tableName, cacheKey); + const createPromise = this.createModelWithRetry(warehouseIdStr, type, tableName, cacheKey); this.creatingTables.set(cacheKey, createPromise); const dynamicModel = await createPromise; @@ -78,34 +183,12 @@ module.exports = app => { async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) { for (let i = 0; i < retryCount; i++) { try { - // 检查表是否存在 - const tableExists = await this.checkTableExists(tableName); - if (!tableExists) { - await this.createPhysicalTable(warehouseId, type); - } + const DynamicModel = this.buildDynamicModel(warehouseId, type, tableName); - // 创建模型实例 - const mainModel = this.app.model.OrderItems; - const attributes = { ...mainModel.rawAttributes }; - - // 移除主键的autoIncrement属性,避免动态表冲突 - if (attributes.id) { - delete attributes.id.autoIncrement; - } - - const DynamicModel = this.app.model.define(tableName, attributes, { - tableName, - timestamps: true, - underscored: true, - paranoid: false, - indexes: this.generateIndexes(warehouseId), - comment: type === 'history' - ? `仓库${warehouseId}订单商品历史表` - : `仓库${warehouseId}订单商品常用表`, - }); + await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel); // 复制关联关系 - this.copyAssociations(mainModel, DynamicModel); + this.copyAssociations(this.app.model.OrderItems, DynamicModel); // 缓存模型 this.modelCache.set(cacheKey, DynamicModel); @@ -150,6 +233,56 @@ module.exports = app => { } } + /** + * 构建订单商品动态模型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {string} type 模型类型。 + * @param {string} tableName 表名。 + * @return {Object} 动态模型。 + */ + buildDynamicModel(warehouseId, type, tableName) { + const attributes = this.getTableAttributes(type); + const modelComment = type === 'history' + ? `仓库${warehouseId}订单商品历史表` + : type === 'dispatch' + ? `仓库${warehouseId}订单商品配送表` + : `仓库${warehouseId}订单商品常用表`; + + return this.app.model.define(tableName, attributes, { + tableName, + timestamps: true, + underscored: true, + paranoid: false, + indexes: this.generateIndexes(warehouseId), + comment: modelComment, + }); + } + + /** + * 获取订单商品模型属性定义。 + * @param {string} type 模型类型。 + * @return {Object} 属性定义。 + */ + getTableAttributes(type) { + const mainModel = this.app.model.OrderItems; + const attributes = cloneAttributes(mainModel && mainModel.rawAttributes); + + if (attributes.id) { + delete attributes.id.autoIncrement; + } + + if (type === 'history' && !attributes.archive_time) { + attributes.archive_time = { + type: this.app.Sequelize.DATE, + allowNull: true, + defaultValue: this.app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '归档时间', + }; + } + + return attributes; + } + /** * 生成索引配置 * @param {number} warehouseId 仓库ID @@ -206,7 +339,9 @@ module.exports = app => { type: Sequelize.QueryTypes.SELECT, } ); - return !!results; + return Array.isArray(results) + ? results.length > 0 + : Boolean(results); } catch (error) { this.app.logger.error('检查表是否存在失败:', error); return false; @@ -214,55 +349,130 @@ module.exports = app => { } /** - * 创建物理表 + * 判断目标表是否需要进行结构同步。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {boolean|null} [tableExists=null] 是否已确认表存在。 + * @return {Promise} 是否需要同步。 + */ + async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) { + const queryInterface = this.app.model.getQueryInterface(); + const managedTableExists = typeof tableExists === 'boolean' + ? tableExists + : await this.checkTableExists(tableName); + + if (!managedTableExists) { + return true; + } + + const [ tables, indexes ] = await Promise.all([ + queryInterface.describeTable(tableName), + typeof queryInterface.showIndex === 'function' + ? queryInterface.showIndex(tableName) + : Promise.resolve([]), + ]); + + const expectedAttributes = this.getTableAttributes(type); + const expectedAttributeNames = Object.keys(expectedAttributes); + const actualAttributeNames = Object.keys(tables || {}); + + if (expectedAttributeNames.length !== actualAttributeNames.length) { + return true; + } + + const actualColumnNames = new Set(actualAttributeNames); + + for (const columnName of expectedAttributeNames) { + if (!actualColumnNames.has(columnName)) { + return true; + } + } + + for (const columnName of expectedAttributeNames) { + const expectedColumn = expectedAttributes[columnName]; + const actualColumn = tables[columnName] || {}; + const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function' + ? expectedColumn.type.toSql().toLowerCase() + : String(expectedColumn.type || '').toLowerCase(); + const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase(); + const expectedAllowNull = expectedColumn.allowNull !== false; + const actualAllowNull = actualColumn.allowNull !== false; + const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue') + ? expectedColumn.defaultValue + : undefined; + const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue') + ? actualColumn.defaultValue + : undefined; + + if (expectedType && actualType && expectedType !== actualType) { + return true; + } + + if (expectedAllowNull !== actualAllowNull) { + return true; + } + + const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault); + const normalizedActualDefault = actualDefault == null ? null : String(actualDefault); + + if (normalizedExpectedDefault !== normalizedActualDefault) { + return true; + } + } + + const expectedIndexes = this.generateIndexes(warehouseId); + const actualIndexes = Array.isArray(indexes) ? indexes : []; + + for (const expectedIndex of expectedIndexes) { + const actualIndex = actualIndexes.find(index => (index.Key_name || index.name) === expectedIndex.name); + + if (!actualIndex) { + return true; + } + + if (isIndexDefinitionDifferent(expectedIndex, actualIndex)) { + return true; + } + } + + return false; + } + + /** + * 确保目标表与模型结构一致。 + * @param {string} tableName 表名。 + * @param {string} type 模型类型。 + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [DynamicModel] 已构建的动态模型。 + * @return {Promise} 是否执行了同步。 + */ + async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) { + const dynamicModel = DynamicModel || this.buildDynamicModel(warehouseId, type, tableName); + const tableExists = await this.checkTableExists(tableName); + const needsSync = tableExists + ? await this.needsTableSchemaSync(tableName, type, warehouseId, tableExists) + : true; + + if (!needsSync) { + return false; + } + + await dynamicModel.sync({ alter: true }); + return true; + } + + /** + * 创建物理表。 * @param {number} warehouseId 仓库ID * @param {string} type 模型类型 */ async createPhysicalTable(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); - const tableComment = type === 'history' - ? `仓库${warehouseId}订单商品历史表` - : `仓库${warehouseId}订单商品常用表`; + const dynamicModel = this.buildDynamicModel(warehouseId, type, tableName); - // 历史表特有字段 - const historyFields = type === 'history' ? - ',`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; - - const createTableSQL = ` - CREATE TABLE IF NOT EXISTS \`${tableName}\` ( - \`id\` bigint(20) unsigned NOT NULL AUTO_INCREMENT, - \`order_id\` bigint(20) unsigned DEFAULT NULL COMMENT '订单ID', - \`actual_price\` decimal(18,2) NOT NULL DEFAULT '0.00' COMMENT '实际价格', - \`retail_price\` decimal(18,2) DEFAULT NULL COMMENT '零售价格', - \`ext_code\` varchar(50) DEFAULT NULL COMMENT '外部编码', - \`inventory_type\` varchar(50) DEFAULT NULL COMMENT '库存类型', - \`item_code\` varchar(50) DEFAULT NULL COMMENT '商品编码', - \`item_id\` bigint(20) DEFAULT NULL COMMENT '商品ID', - \`item_name\` varchar(200) DEFAULT NULL COMMENT '商品名称', - \`order_line_no\` varchar(50) DEFAULT NULL COMMENT '订单行号', - \`owner_code\` varchar(50) DEFAULT NULL COMMENT '货主编码', - \`plan_qty\` int(11) DEFAULT NULL COMMENT '计划数量', - \`source_order_code\` varchar(50) DEFAULT NULL COMMENT '源订单编码', - \`sub_source_order_code\` varchar(50) DEFAULT NULL COMMENT '子源订单编码', - \`extend_props\` json DEFAULT NULL COMMENT '扩展属性(JSON格式)', - \`stock_id\` bigint(20) DEFAULT NULL COMMENT '库存ID', - \`created_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - \`updated_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间' - ${historyFields}, - PRIMARY KEY (\`id\`), - KEY \`idx_${warehouseId}_order_id\` (\`order_id\`), - KEY \`idx_${warehouseId}_item_id\` (\`item_id\`), - KEY \`idx_${warehouseId}_item_code\` (\`item_code\`), - KEY \`idx_${warehouseId}_source_order_code\` (\`source_order_code\`), - KEY \`idx_${warehouseId}_stock_id\` (\`stock_id\`), - KEY \`idx_${warehouseId}_owner_code\` (\`owner_code\`), - KEY \`idx_${warehouseId}_order_item\` (\`order_id\`, \`item_id\`), - KEY \`idx_${warehouseId}_created_at\` (\`created_at\`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${tableComment}'; - `; - - await this.app.model.query(createTableSQL); - this.app.logger.info(`创建订单商品物理表成功: ${tableName}`); + await dynamicModel.sync({ alter: true }); + this.app.logger.info(`创建/同步订单商品物理表成功: ${tableName}`); } /** @@ -271,7 +481,11 @@ module.exports = app => { * @param {string} type 模型类型 */ generateTableName(warehouseId, type) { - const suffix = type === 'history' ? '_history' : ''; + const suffix = type === 'history' + ? '_history' + : type === 'dispatch' + ? '_dispatch' + : ''; return `wms_order_items_${warehouseId}${suffix}`; } @@ -283,6 +497,8 @@ module.exports = app => { clearCache(warehouseId, type) { const cacheKey = `${warehouseId}_${type}`; this.modelCache.delete(cacheKey); + this.creatingTables.delete(cacheKey); + clearShardWarehouseValidationCache(this.app); } /** @@ -290,6 +506,8 @@ module.exports = app => { */ clearAllCache() { this.modelCache.clear(); + this.creatingTables.clear(); + clearShardWarehouseValidationCache(this.app); } /** diff --git a/app/model/picking.js b/app/model/picking.js new file mode 100644 index 0000000..34c7daa --- /dev/null +++ b/app/model/picking.js @@ -0,0 +1,128 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE, INTEGER } = app.Sequelize; + + const Picking = app.model.define('picking', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库存记录ID', + }, + quantity: { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '分配数量', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + space_name: { + type: STRING(100), + allowNull: true, + comment: '库位名称', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_picking', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '订单储位分配表', + indexes: [ + { + name: 'idx_wms_picking_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_wms_picking_order_item_id', + fields: [ 'order_item_id' ], + }, + { + name: 'idx_wms_picking_storage_id', + fields: [ 'storage_id' ], + }, + { + name: 'idx_wms_picking_space_id', + fields: [ 'space_id' ], + }, + { + name: 'idx_wms_picking_status', + fields: [ 'status' ], + }, + { + name: 'idx_wms_picking_order_item_space', + fields: [ 'order_item_id', 'space_id' ], + }, + ], + }); + + Picking.associate = function() { + const { OrderItems, Storage, LocationSpace } = app.model; + + if (OrderItems) { + Picking.belongsTo(OrderItems, { + foreignKey: 'order_item_id', + as: 'orderItem', + constraints: false, + }); + } + + if (Storage) { + Picking.belongsTo(Storage, { + foreignKey: 'storage_id', + as: 'storageRecord', + constraints: false, + }); + } + + if (LocationSpace) { + Picking.belongsTo(LocationSpace, { + foreignKey: 'space_id', + as: 'space', + constraints: false, + }); + } + }; + + return Picking; +}; \ No newline at end of file diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index ea749c5..97f4946 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -191,6 +191,26 @@ module.exports = app => { type: INTEGER(11).UNSIGNED, defaultValue: 0, }, + inbound_min_days:{ + type: INTEGER(11), + defaultValue: 0, + comment: '入库最小天数要求', + }, + outbound_min_days:{ + type: INTEGER(11), + defaultValue: 0, + comment: '出库最小天数要求', + }, + shelf_life_days:{ + type: INTEGER(11), + defaultValue: 0, + comment: '保质期天数', + }, + remaining_threshold_days:{ + type: INTEGER(11), + defaultValue: 0, + comment: '剩余有效期阈值天数', + }, deleted_at: { type: DATE, defaultValue: null, diff --git a/app/model/store.js b/app/model/store.js index b59e68e..4452456 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -5,8 +5,19 @@ module.exports = app => { const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; const DEFAULT_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + default_express_code: 'STO', + default_platform_code: 'TB', }); + const normalizeSubjectConfigText = (value, defaultValue) => { + if (value === undefined || value === null) { + return defaultValue; + } + + const normalized = String(value).trim(); + return normalized === '' ? defaultValue : normalized; + }; + const normalizeBooleanFlag = (value, fieldName) => { if (value === undefined || value === null || value === '') { return undefined; @@ -56,6 +67,15 @@ module.exports = app => { normalized.max_notice_webhook_count = limit; } + normalized.default_express_code = normalizeSubjectConfigText( + parsed.default_express_code, + DEFAULT_SUBJECT_CONFIG.default_express_code + ); + normalized.default_platform_code = normalizeSubjectConfigText( + parsed.default_platform_code, + DEFAULT_SUBJECT_CONFIG.default_platform_code + ); + if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) { normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled'); } diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index f1ffa84..3b6e785 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -11,16 +11,11 @@ module.exports = app => { default: 'standard', required: false, description: '控制货主在该仓下的收货校验模式', - options: [ 'standard', 'strict', 'manual' ], - }), - Object.freeze({ - key: 'sku_visibility', - name: 'SKU 可见范围', - type: 'enum', - default: 'all', - required: false, - description: '控制货主在该仓下的 SKU 可见策略', - options: [ 'all', 'whitelist', 'blacklist' ], + options: [ + Object.freeze({ value: 'standard', label: '标准收货' }), + Object.freeze({ value: 'strict', label: '严格收货' }), + Object.freeze({ value: 'manual', label: '人工收货' }), + ], }), Object.freeze({ key: 'auto_allocate_bin', @@ -46,6 +41,14 @@ module.exports = app => { required: false, description: '是否允许进入临时存放区', }), + Object.freeze({ + key: 'storage_separation', + name: '是否存储分离', + type: 'flag', + default: 1, + required: false, + description: '控制该货主在当前仓库下是否按独立存储策略管理库存', + }), Object.freeze({ key: 'allow_oversell', name: '允许超卖', @@ -62,6 +65,22 @@ module.exports = app => { required: false, description: '控制货主推送订单创建后是否必须进入审批流程', }), + Object.freeze({ + key: 'default_express_code', + name: '默认快递', + type: 'list', + default: 'STO', + required: false, + description: '货主在当前仓下默认使用的快递编码', + }), + Object.freeze({ + key: 'default_platform_code', + name: '默认平台', + type: 'list', + default: 'TB', + required: false, + description: '货主在当前仓下默认使用的平台编码', + }), Object.freeze({ key: 'print_recharge_price', name: '面单充值元/单', @@ -99,6 +118,38 @@ module.exports = app => { return result; }, {})); + const clonePolicyConfigOptions = options => { + if (!Array.isArray(options)) { + return undefined; + } + + return options.map(option => { + if (!option || typeof option !== 'object') { + return option; + } + + return { ...option }; + }); + }; + + const getPolicyConfigOptionValue = option => { + if (option && typeof option === 'object') { + if (option.value !== undefined && option.value !== null) { + return String(option.value); + } + + if (option.code !== undefined && option.code !== null) { + return String(option.code); + } + + if (option.key !== undefined && option.key !== null) { + return String(option.key); + } + } + + return String(option); + }; + const clonePolicyConfigField = field => ({ key: field.key, name: field.name, @@ -106,7 +157,7 @@ module.exports = app => { default: field.default, required: field.required, description: field.description, - ...(Array.isArray(field.options) ? { options: [ ...field.options ] } : {}), + ...(Array.isArray(field.options) ? { options: clonePolicyConfigOptions(field.options) } : {}), ...(field.min !== undefined ? { min: field.min } : {}), ...(field.max !== undefined ? { max: field.max } : {}), ...(field.precision !== undefined ? { precision: field.precision } : {}), @@ -114,6 +165,26 @@ module.exports = app => { ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), }); + const normalizePolicyConfigOptionValue = option => { + if (!option || typeof option !== 'object') { + return String(option); + } + + if (option.value !== undefined && option.value !== null) { + return String(option.value); + } + + if (option.code !== undefined && option.code !== null) { + return String(option.code); + } + + if (option.key !== undefined && option.key !== null) { + return String(option.key); + } + + return ''; + }; + const parsePolicyConfig = (value, fieldName = 'policy_config') => { if (typeof value === 'string') { try { @@ -167,13 +238,24 @@ module.exports = app => { try { if (field.type === 'enum') { const valueText = String(rawValue).trim(); - if (!field.options.includes(valueText)) { + const allowedValues = Array.isArray(field.options) + ? field.options.map(getPolicyConfigOptionValue) + : []; + if (!allowedValues.includes(valueText)) { throw new Error(`${fieldName}.${field.key} 参数不合法`); } normalized[field.key] = valueText; continue; } + if (field.type === 'list') { + const valueText = String(rawValue).trim(); + if (valueText) { + normalized[field.key] = valueText; + } + continue; + } + if (field.type === 'flag') { if (rawValue === true || rawValue === 1 || rawValue === '1') { normalized[field.key] = 1; @@ -481,6 +563,47 @@ module.exports = app => { return POLICY_CONFIG_FIELDS.map(clonePolicyConfigField); }; + StoreWarehouse.getPolicyConfigFieldListWithOptions = async function() { + const fieldList = this.getPolicyConfigFieldList(); + const [ expressRows, platformRows ] = await Promise.all([ + app.model.Express && typeof app.model.Express.findAll === 'function' + ? app.model.Express.findAll({ + attributes: [ 'code', 'name' ], + order: [ [ 'code', 'ASC' ] ], + }) + : Promise.resolve([]), + app.model.Platform && typeof app.model.Platform.findAll === 'function' + ? app.model.Platform.findAll({ + attributes: [ 'code', 'name' ], + order: [ [ 'code', 'ASC' ] ], + }) + : Promise.resolve([]), + ]); + + const optionMap = { + default_express_code: expressRows.map(item => ({ + value: normalizePolicyConfigOptionValue(item), + label: String(item.name || item.code || ''), + })), + default_platform_code: platformRows.map(item => ({ + value: normalizePolicyConfigOptionValue(item), + label: String(item.name || item.code || ''), + })), + }; + + return fieldList.map(field => { + const options = optionMap[field.key]; + if (!options) { + return field; + } + + return { + ...field, + options, + }; + }); + }; + StoreWarehouse.normalizePolicyConfig = function(value, options = {}) { return normalizePolicyConfig(value, options); }; diff --git a/app/router.js b/app/router.js index 0914efe..58d4c92 100644 --- a/app/router.js +++ b/app/router.js @@ -14,6 +14,10 @@ module.exports = app => { // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); + // 独立 docs 目录挂载 + router.get('/docs', controller.docs.docsIndex); + router.get('/docs/:relPath(.*)', controller.docs.docsFile); + // api文档相关 router.get('/api/docs', controller.docs.list); router.get('/api/docs/:docName/raw', controller.docs.raw); @@ -30,6 +34,9 @@ module.exports = app => { // 临时 fileWriter 消费入口 router.get('/__temp/file-writer/consume', controller.tempFileWriter.consume); + // Polo API 测试入口 + router.get('/testPoloApi', controller.home.testPoloApi); + // 测试接口 router.get('/testSendData', controller.home.testSendData); }; diff --git a/app/schedule/notice_stock_remaining.js b/app/schedule/notice_stock_remaining.js new file mode 100644 index 0000000..735fe88 --- /dev/null +++ b/app/schedule/notice_stock_remaining.js @@ -0,0 +1,733 @@ +'use strict'; + +const CACHE_KEY_PREFIX = 'notice_stock_remaining_notified'; +const LEGACY_CACHE_KEY = 'notice_stock_remaining_notified_list'; +const CACHE_TTL_SECONDS = 24 * 60 * 60; +const DAY_MS = 24 * 60 * 60 * 1000; +const NOTICE_EVENT = 'storage_transfer_completed'; + +/** + * 生成本地日期键,格式为 `YYYYMMDD`。 + * @param {Date} [dateValue=new Date()] 日期对象 + * @return {string} 日期键 + */ +function buildDateKey(dateValue = new Date()) { + const year = String(dateValue.getFullYear()); + const month = String(dateValue.getMonth() + 1).padStart(2, '0'); + const day = String(dateValue.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; +} + +/** + * 生成商品维度的日粒度缓存键。 + * @param {number} stockId 商品ID + * @param {Date} [dateValue=new Date()] 日期对象 + * @return {string} 缓存键 + */ +function buildStockDayCacheKey(stockId, dateValue = new Date()) { + const normalizedStockId = toNumber(stockId, 0); + if (normalizedStockId <= 0) { + return ''; + } + + return `${CACHE_KEY_PREFIX}:stock:${normalizedStockId}:${buildDateKey(dateValue)}`; +} + +/** + * 从记录对象中安全读取字段,兼容下划线和驼峰命名。 + * @param {object} record 记录对象 + * @param {string[]} fieldNames 候选字段名列表 + * @return {*} 命中的字段值 + */ +function readRecordValue(record, fieldNames) { + if (!record || !Array.isArray(fieldNames)) { + return undefined; + } + + for (const fieldName of fieldNames) { + if (!fieldName) { + continue; + } + + if (Object.prototype.hasOwnProperty.call(record, fieldName)) { + return record[fieldName]; + } + + if (record.dataValues && Object.prototype.hasOwnProperty.call(record.dataValues, fieldName)) { + return record.dataValues[fieldName]; + } + + if (typeof record.getDataValue === 'function') { + try { + const dataValue = record.getDataValue(fieldName); + if (dataValue !== undefined) { + return dataValue; + } + } catch (error) { + // 忽略单个字段读取失败,继续尝试其他候选字段。 + } + } + + if (typeof record.get === 'function') { + try { + const getterValue = record.get(fieldName); + if (getterValue !== undefined) { + return getterValue; + } + } catch (error) { + // 忽略单个字段读取失败,继续尝试其他候选字段。 + } + } + } + + return undefined; +} + +/** + * 将数值安全转换为数字。 + * @param {*} value 原始值 + * @param {number} [fallback=0] 转换失败时的兜底值 + * @return {number} 数值结果 + */ +function toNumber(value, fallback = 0) { + const numberValue = Number(value); + return Number.isFinite(numberValue) ? numberValue : fallback; +} + +/** + * 归一化历史全局缓存中的已通知列表。 + * + * 注意:该方法仅用于兼容旧格式的观测或迁移,不再参与新去重逻辑, + * 避免旧的全局列表继续抑制当天的通知。 + * + * @param {*} rawValue 缓存原始值 + * @return {string[]} 标准化后的通知键列表 + */ +function normalizeNotifiedList(rawValue) { + if (!rawValue) { + return []; + } + + let parsedValue = rawValue; + + if (typeof rawValue === 'string') { + try { + parsedValue = JSON.parse(rawValue); + } catch (error) { + return []; + } + } + + const list = Array.isArray(parsedValue) + ? parsedValue + : (typeof parsedValue === 'object' && parsedValue !== null + ? Object.values(parsedValue) + : []); + + return list.map(item => { + if (item && typeof item === 'object') { + const stockId = readRecordValue(item, [ 'stock_id', 'stockId' ]); + if (stockId !== undefined && stockId !== null && String(stockId).trim() !== '') { + return `stock:${String(stockId)}`; + } + + const itemId = readRecordValue(item, [ 'id', 'storage_id', 'storageId' ]); + if (itemId !== undefined && itemId !== null && String(itemId).trim() !== '') { + return `storage:${String(itemId)}`; + } + } + + const normalizedValue = String(item || '').trim(); + if (!normalizedValue) { + return ''; + } + + if (normalizedValue.startsWith('storage:')) { + return normalizedValue; + } + + if (/^\d+$/.test(normalizedValue)) { + return `storage:${normalizedValue}`; + } + + return normalizedValue; + }).filter(Boolean); +} + +/** + * 生成库存记录对应的商品级通知去重键。 + * @param {object} storageRecord 库存记录 + * @return {string} 去重键 + */ +function buildStockNotifyKey(storageRecord) { + const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0); + return stockId > 0 ? `stock:${stockId}` : ''; +} + +/** + * 按商品 ID 对库存记录进行分组。 + * @param {object[]} storageRows 库存记录列表 + * @return {Map} 分组后的库存记录映射 + */ +function groupStorageRowsByStockId(storageRows) { + const groupedStorageRows = new Map(); + + if (!Array.isArray(storageRows)) { + return groupedStorageRows; + } + + for (const storageRow of storageRows) { + const stockId = toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0); + if (stockId <= 0) { + continue; + } + + const stockStorageRows = groupedStorageRows.get(stockId) || []; + stockStorageRows.push(storageRow); + groupedStorageRows.set(stockId, stockStorageRows); + } + + return groupedStorageRows; +} + +/** + * 格式化日期字符串,优先使用应用内格式化器。 + * @param {object} ctx Egg 上下文 + * @param {*} value 原始日期值 + * @return {string} 格式化后的日期字符串 + */ +function formatDate(ctx, value) { + if (!value) { + return ''; + } + + const dateValue = value instanceof Date ? value : new Date(value); + if (Number.isNaN(dateValue.getTime())) { + return ''; + } + + if (ctx && ctx.app && typeof ctx.app.formatDate === 'function') { + return ctx.app.formatDate(dateValue); + } + + return dateValue.toISOString(); +} + +/** + * 生成库存效期预警通知内容。 + * @param {object} params 参数对象 + * @param {object} params.ctx Egg 上下文 + * @param {object} params.storageRecord 库存记录 + * @param {object} params.stockRecord 商品主数据 + * @param {number} params.remainingDays 剩余天数 + * @param {number} params.thresholdDays 预警阈值天数 + * @return {string} 通知正文 + */ +function buildNoticeContent({ ctx, storageRecord, stockRecord, remainingDays, thresholdDays }) { + const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0); + const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0); + const itemCode = String(readRecordValue(stockRecord, [ 'item_code', 'itemCode' ]) || '').trim() || String(stockId || storageId); + const itemName = String(readRecordValue(stockRecord, [ 'item_name', 'itemName' ]) || '').trim() || '未命名商品'; + const batchNo = String(readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '').trim() || '无'; + const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]), 0); + const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]), 0); + const expiryDate = formatDate(ctx, readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ])); + const inboundTime = formatDate(ctx, readRecordValue(storageRecord, [ 'inbound_time', 'inboundTime' ])); + const quantity = toNumber(readRecordValue(storageRecord, [ 'quantity' ]), 0); + const availableQuantity = toNumber(readRecordValue(storageRecord, [ 'available_quantity', 'availableQuantity' ]), quantity); + const spaceRecord = readRecordValue(storageRecord, [ 'space' ]) || storageRecord.space || {}; + const spaceCode = String(readRecordValue(spaceRecord, [ 'space_code', 'spaceCode' ]) || '').trim(); + const spaceName = String(readRecordValue(spaceRecord, [ 'custom_name', 'customName' ]) || '').trim(); + const spaceLabel = [ spaceCode, spaceName ].filter(Boolean).join(' / ') || '无'; + + return [ + `库存效期预警:${itemName}`, + `商品编码:${itemCode}`, + `库存ID:${storageId || '未知'}`, + `批次号:${batchNo}`, + `仓库ID:${warehouseId || '未知'}`, + `货主ID:${storeId || '未知'}`, + `库位:${spaceLabel}`, + `库存数量:${quantity}`, + `可用数量:${availableQuantity}`, + `效期日期:${expiryDate || '未知'}`, + `剩余天数:${remainingDays}`, + `预警阈值:${thresholdDays}`, + `入库时间:${inboundTime || '未知'}`, + ].join('\n'); +} + +/** + * 解析库存效期预警通知的发送方法,优先使用 `send`,其次兼容 `index.send`。 + * @param {object} ctx Egg 上下文 + * @return {Function|null} 可执行的发送方法 + */ +function resolveNoticeSendMethod(ctx) { + const noticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + if (!noticeService) { + return null; + } + + if (typeof noticeService.send === 'function') { + return noticeService.send.bind(noticeService); + } + + if (noticeService.index && typeof noticeService.index.send === 'function') { + return noticeService.index.send.bind(noticeService.index); + } + + return null; +} + +/** + * 发送库存效期预警通知。 + * @param {object} ctx Egg 上下文 + * @param {object} payload 通知参数 + * @return {Promise} 通知发送结果 + */ +async function sendStockRemainingNotice(ctx, payload) { + const sendMethod = resolveNoticeSendMethod(ctx); + if (typeof sendMethod !== 'function') { + throw new Error('通知服务不可用'); + } + + return await sendMethod(payload); +} + +module.exports = { + schedule: { + interval: '30s', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行库存效期预警扫描。 + * @param {object} ctx Egg 上下文 + * @return {Promise} + */ + async task(ctx) { + const scheduleName = 'notice_stock_remaining'; + let stockCount = 0; + let storageCount = 0; + let sentCount = 0; + let skippedCount = 0; + const today = new Date(); + + ctx.logger.info(`[${scheduleName}] 本轮任务启动`, { + scheduleName, + cacheKeyPrefix: CACHE_KEY_PREFIX, + running: Boolean(ctx.app._noticeStockRemainingRunning), + }); + + if (ctx.app._noticeStockRemainingRunning) { + ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`, { + scheduleName, + cacheKeyPrefix: CACHE_KEY_PREFIX, + running: Boolean(ctx.app._noticeStockRemainingRunning), + }); + return; + } + + ctx.app._noticeStockRemainingRunning = true; + + try { + const legacyCachedValue = typeof ctx.app.getCacheAsync === 'function' + ? await ctx.app.getCacheAsync(LEGACY_CACHE_KEY) + : null; + const legacyCacheHit = legacyCachedValue !== null && legacyCachedValue !== undefined; + const legacyNotifiedList = normalizeNotifiedList(legacyCachedValue); + + ctx.logger.info('[notice_stock_remaining] 已检查历史通知缓存', { + legacyCacheKey: LEGACY_CACHE_KEY, + cacheHit: legacyCacheHit, + cachedValueType: Array.isArray(legacyCachedValue) ? 'array' : typeof legacyCachedValue, + rawCacheCount: Array.isArray(legacyCachedValue) ? legacyCachedValue.length : 0, + normalizedCount: legacyNotifiedList.length, + cacheKeyMode: 'stock-day', + }); + + if (legacyCacheHit) { + ctx.logger.warn('[notice_stock_remaining] 检测到旧的全局去重缓存,当前版本不再使用该缓存参与拦截', { + legacyCacheKey: LEGACY_CACHE_KEY, + normalizedCount: legacyNotifiedList.length, + }); + } + + ctx.logger.debug('[notice_stock_remaining] 日粒度去重已启用', { + cacheKeyPrefix: CACHE_KEY_PREFIX, + dateKey: buildDateKey(today), + }); + + const stockWhere = { + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: { + [ctx.app.Sequelize.Op.gt]: 0, + }, + }; + + const stockRows = await ctx.model.StockWarehouse.findAll({ + attributes: [ + 'id', + 'item_code', + 'item_name', + 'store_id', + 'warehouse_id', + 'remaining_threshold_days', + ], + where: stockWhere, + order: [[ 'remaining_threshold_days', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + stockCount = Array.isArray(stockRows) ? stockRows.length : 0; + ctx.logger.info('[notice_stock_remaining] 完成商品候选查询', { + stockCount, + }); + + if (Array.isArray(stockRows)) { + for (const stockRow of stockRows) { + ctx.logger.debug('[notice_stock_remaining] 商品候选明细', { + id: toNumber(readRecordValue(stockRow, [ 'id' ]), 0), + item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(), + remaining_threshold_days: Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0))), + }); + } + } + + if (!Array.isArray(stockRows) || stockRows.length === 0) { + ctx.logger.info('[notice_stock_remaining] 未找到开启效期管理且阈值大于 0 的商品'); + return; + } + + const stockMap = new Map(); + let maxThresholdDays = 0; + + for (const stockRow of stockRows) { + const stockId = toNumber(readRecordValue(stockRow, [ 'id' ]), 0); + const thresholdDays = Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0))); + + if (stockId <= 0 || thresholdDays <= 0) { + continue; + } + + stockMap.set(stockId, { + id: stockId, + item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(), + item_name: String(readRecordValue(stockRow, [ 'item_name', 'itemName' ]) || '').trim(), + store_id: toNumber(readRecordValue(stockRow, [ 'store_id', 'storeId' ]), 0), + warehouse_id: toNumber(readRecordValue(stockRow, [ 'warehouse_id', 'warehouseId' ]), 0), + remaining_threshold_days: thresholdDays, + }); + + if (thresholdDays > maxThresholdDays) { + maxThresholdDays = thresholdDays; + } + } + + const stockIds = Array.from(stockMap.keys()); + if (stockIds.length === 0 || maxThresholdDays <= 0) { + ctx.logger.info('[notice_stock_remaining] 商品数据中没有可用的效期预警阈值', { + stockCount, + validStockCount: stockIds.length, + maxThresholdDays, + }); + return; + } + + const now = new Date(); + const maxExpiryDate = new Date(now.getTime() + (maxThresholdDays * DAY_MS)); + const storageWhere = { + stock_id: { + [ctx.app.Sequelize.Op.in]: stockIds, + }, + is_enabled: 1, + delete_at: null, + quantity: { + [ctx.app.Sequelize.Op.gt]: 0, + }, + expiry_date: { + [ctx.app.Sequelize.Op.ne]: null, + [ctx.app.Sequelize.Op.lte]: maxExpiryDate, + }, + }; + + const storageRows = await ctx.model.Storage.findAll({ + where: storageWhere, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'space_code', 'custom_name' ], + required: false, + }, + ], + order: [[ 'expiry_date', 'ASC' ], [ 'inbound_time', 'ASC' ], [ 'id', 'ASC' ]], + }); + + storageCount = Array.isArray(storageRows) ? storageRows.length : 0; + + ctx.logger.info('[notice_stock_remaining] 完成库存候选查询', { + stockCount: stockIds.length, + storageCount, + maxThresholdDays, + }); + + if (Array.isArray(storageRows)) { + for (const storageRow of storageRows) { + ctx.logger.debug('[notice_stock_remaining] 库存候选明细', { + id: toNumber(readRecordValue(storageRow, [ 'id', 'storage_id', 'storageId' ]), 0), + stock_id: toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0), + expiry_date: formatDate(ctx, readRecordValue(storageRow, [ 'expiry_date', 'expiryDate' ])), + quantity: toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0), + available_quantity: toNumber(readRecordValue(storageRow, [ 'available_quantity', 'availableQuantity' ]), toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0)), + }); + } + } + + const groupedStorageRows = groupStorageRowsByStockId(storageRows); + const representativeStorageRows = Array.from(groupedStorageRows.values()).map(stockStorageRows => stockStorageRows[0]); + + for (const storageRecord of representativeStorageRows) { + const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0); + const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0); + const notifyKey = buildStockNotifyKey(storageRecord); + const stockDayCacheKey = buildStockDayCacheKey(stockId, today); + const stockRecord = stockMap.get(stockId); + const thresholdDays = stockRecord ? toNumber(readRecordValue(stockRecord, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0) : 0; + + if (!notifyKey) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + reason: 'notifyKey 为空', + }); + continue; + } + + if (!stockDayCacheKey) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + reason: '日粒度缓存键为空', + }); + continue; + } + + if (!stockRecord) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + reason: '未找到对应商品记录', + }); + continue; + } + + if (typeof ctx.app.getCacheAsync === 'function') { + const cachedNotifiedValue = await ctx.app.getCacheAsync(stockDayCacheKey); + if (cachedNotifiedValue !== null && cachedNotifiedValue !== undefined) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + reason: '当日已通知过该商品', + }); + continue; + } + } + + if (thresholdDays <= 0) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + reason: '商品阈值小于等于 0', + }); + continue; + } + + const expiryDateValue = readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ]); + if (!expiryDateValue) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + reason: '缺少效期日期', + }); + continue; + } + + const expiryDate = expiryDateValue instanceof Date ? expiryDateValue : new Date(expiryDateValue); + if (Number.isNaN(expiryDate.getTime())) { + ctx.logger.warn('[notice_stock_remaining] 跳过非法效期日期', { + storageId, + stockId, + expiryDate: String(expiryDateValue), + }); + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + reason: '效期日期非法', + }); + continue; + } + + const remainingDays = Math.max(0, Math.ceil((expiryDate.getTime() - now.getTime()) / DAY_MS)); + if (remainingDays > thresholdDays) { + skippedCount += 1; + ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', { + storageId, + stockId, + notifyKey, + thresholdDays, + remainingDays, + reason: '剩余天数大于阈值', + }); + continue; + } + + const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]) || stockRecord.warehouse_id, 0); + const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]) || stockRecord.store_id, 0); + const title = `库存效期预警:${stockRecord.item_name || '未命名商品'}`; + const content = buildNoticeContent({ + ctx, + storageRecord, + stockRecord, + remainingDays, + thresholdDays, + }); + + ctx.logger.info('[notice_stock_remaining] 进入发送分支', { + storageId, + stockId, + notifyKey, + remainingDays, + thresholdDays, + warehouseId, + storeId, + }); + + try { + const noticeResult = await sendStockRemainingNotice(ctx, { + warehouseId, + storeId, + subject: { + id: warehouseId, + type: 'warehouse', + name: `仓库${warehouseId || '未知'}`, + }, + businessName: 'storage', + event: NOTICE_EVENT, + title, + content, + businessId: stockId, + messageType: 'text', + metadata: { + cacheKey: stockDayCacheKey, + storageId, + stockId, + notifyKey, + businessId: stockId, + thresholdDays, + remainingDays, + warehouseId, + storeId, + stock: { + id: stockRecord.id, + item_code: stockRecord.item_code, + item_name: stockRecord.item_name, + }, + storage: { + id: storageId, + batch_no: readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '', + expiry_date: expiryDate.toISOString(), + }, + }, + }); + + if (noticeResult && noticeResult.success === false) { + ctx.logger.warn('[notice_stock_remaining] 通知发送失败,保留待重试状态', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + remainingDays, + thresholdDays, + result: noticeResult, + }); + continue; + } + + if (typeof ctx.app.setCacheAsync === 'function') { + await ctx.app.setCacheAsync(stockDayCacheKey, { + notifiedAt: today.toISOString(), + stockId, + notifyKey, + }, CACHE_TTL_SECONDS); + } + sentCount += 1; + + ctx.logger.info('[notice_stock_remaining] 库存效期预警已发送', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + remainingDays, + thresholdDays, + result: noticeResult, + }); + } catch (noticeError) { + ctx.logger.error('[notice_stock_remaining] 库存效期预警发送异常', { + storageId, + stockId, + notifyKey, + stockDayCacheKey, + remainingDays, + thresholdDays, + error: noticeError.message, + stack: noticeError.stack, + }); + } + } + + ctx.logger.info('[notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写', { + cacheKeyPrefix: CACHE_KEY_PREFIX, + sentCount, + skippedCount, + ttlSeconds: CACHE_TTL_SECONDS, + }); + } catch (error) { + ctx.logger.error('[notice_stock_remaining] 执行失败', { + error: error.message, + stack: error.stack, + }); + } finally { + ctx.app._noticeStockRemainingRunning = false; + ctx.logger.info('[notice_stock_remaining] 本轮任务结束', { + scheduleName, + cacheKeyPrefix: CACHE_KEY_PREFIX, + stockCount, + storageCount, + sentCount, + skippedCount, + running: Boolean(ctx.app._noticeStockRemainingRunning), + }); + } + }, +}; diff --git a/app/schedule/sync_outbound_orders_to_delivery.js b/app/schedule/sync_outbound_orders_to_delivery.js new file mode 100644 index 0000000..804fa8d --- /dev/null +++ b/app/schedule/sync_outbound_orders_to_delivery.js @@ -0,0 +1,51 @@ +'use strict'; + +const SHORT_TASK_QUERY_TIMEOUT_MS = 15000; +const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000; + +/** + * 每 1 分钟在单 worker 中同步一次正常出库订单到配送表。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, + + executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, + + /** + * 执行已出库订单迁移任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._syncOutboundOrdersToDeliveryRunning) { + return; + } + + ctx.app._syncOutboundOrdersToDeliveryRunning = true; + + try { + const result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({ + queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, + executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, + }); + + if (result && result.retryableFailure) { + ctx.logger.warn(`[sync-outbound-orders-to-delivery] 正常迁移遇到 ${result.retryableFailureType},已标记 ${result.timeoutCount || 0} 条订单为出库超时`); + } else if (result && result.totalCreated > 0) { + ctx.logger.info(`[sync-outbound-orders-to-delivery] 同步 ${result.totalCreated} 条已出库订单`); + } + } catch (error) { + ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`); + } finally { + ctx.app._syncOutboundOrdersToDeliveryRunning = false; + } + }, +}; diff --git a/app/schedule/sync_outbound_timeout_orders_to_delivery.js b/app/schedule/sync_outbound_timeout_orders_to_delivery.js new file mode 100644 index 0000000..48556c5 --- /dev/null +++ b/app/schedule/sync_outbound_timeout_orders_to_delivery.js @@ -0,0 +1,51 @@ +'use strict'; + +const LONG_TASK_QUERY_TIMEOUT_MS = 120000; +const LONG_TASK_EXECUTION_TIMEOUT_MS = 300000; + +/** + * 每 10 分钟在单 worker 中重试一次出库超时订单到配送表。 + */ +module.exports = { + schedule: { + interval: '10m', + type: 'worker', + immediate: false, + disable: false, + }, + + queryTimeoutMs: LONG_TASK_QUERY_TIMEOUT_MS, + + executionTimeoutMs: LONG_TASK_EXECUTION_TIMEOUT_MS, + + /** + * 执行出库超时订单重试任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning) { + return; + } + + ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = true; + + try { + const result = await ctx.service.systems.orderDeliveryMigration.retryTimeoutOutboundOrdersToDelivery({ + queryTimeoutMs: LONG_TASK_QUERY_TIMEOUT_MS, + executionTimeoutMs: LONG_TASK_EXECUTION_TIMEOUT_MS, + }); + + if (result && result.retryableFailure) { + ctx.logger.warn(`[sync-outbound-timeout-orders-to-delivery] 重试出库超时订单遇到 ${result.retryableFailureType}`); + } else if (result && result.totalCreated > 0) { + ctx.logger.info(`[sync-outbound-timeout-orders-to-delivery] 重试同步 ${result.totalCreated} 条出库超时订单`); + } + } catch (error) { + ctx.logger.error(`[sync-outbound-timeout-orders-to-delivery] 重试失败: ${error.message}`); + } finally { + ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = false; + } + }, +}; diff --git a/app/service/qimen.js b/app/service/qimen.js index 8e2b44d..1857a9f 100644 --- a/app/service/qimen.js +++ b/app/service/qimen.js @@ -58,12 +58,8 @@ class QimenService extends Service { parseAttributeValue: false, trimValues: false, // 也关闭trim,保持原始格式 ignoreDeclaration: true, - // 添加标签值处理器,手动控制转换 - tagValueProcessor: tagValue => { - // 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理 - // 默认返回原始值 - return tagValue; - }, + // 保持 fast-xml-parser 的真实叶子文本值,避免把标签名误当成字段值。 + tagValueProcessor: (tagName, tagValue) => tagValue, }); try { @@ -233,6 +229,12 @@ class QimenService extends Service { } }); } + /** + * 保存奇门请求日志。 + * @param {Object} logData 日志数据。 + * @param {number} startTime 请求开始时间戳。 + * @return {Promise} 新增日志ID。 + */ async saveQimenLog(logData, startTime) { const { ctx, @@ -252,6 +254,7 @@ class QimenService extends Service { // 使用 egg-mysql 保存日志到数据库 const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', { + log_id: logData.log_id || ctx.qimenLogId || null, from_key: logData.from_key || '', to_key: logData.to_key || '', method: logData.method || '', diff --git a/app/service/qimenMethods/deliveryorder.js b/app/service/qimenMethods/deliveryorder.js index 9ba30c3..6b72beb 100644 --- a/app/service/qimenMethods/deliveryorder.js +++ b/app/service/qimenMethods/deliveryorder.js @@ -31,13 +31,12 @@ class deliveryorderServer extends MainService { } async create(data) { - const info = this.getInfo; - const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, this.getInfo(), 'QM'); + const info = this.getInfo(); + const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, info, 'QM'); if (res.success) { return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); } return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); - } async batchcreate() { return this.fail('批量创建接口未完善'); diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 7161acd..544f425 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -87,13 +87,143 @@ class orderServer extends MainService { }; } + async getInterceptExpressInfo(orderId) { + const { ctx } = this; + const normalizedOrderId = Number(orderId || 0); + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + return []; + } + + const orderExpressModel = ctx.model && ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return []; + } + + const rows = await orderExpressModel.findAll({ + where: { + order_id: normalizedOrderId, + }, + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ], + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + return (Array.isArray(rows) ? rows : []).map(row => ({ + waybill_code: String(row && row.waybill_code || '').trim(), + logistics_code: String(row && row.logistics_code || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id), + })); + } + + async sendCancelInterceptNotice({ orderCode, existingOrder, info }) { + const { ctx } = this; + try { + const express = await this.getInterceptExpressInfo(existingOrder && existingOrder.id); + + await ctx.service.systems.notice.send({ + event: 'order_cancel_intercepted', + businessName: 'order', + warehouseId: info.warehouseId, + storeId: info.storeId, + subject: { + id: info.storeId, + type: 'store', + }, + businessId: orderCode, + messageType: 'text', + title: `订单取消触发拦截:${orderCode}`, + content: `订单 ${orderCode} 因拣货/打印状态未完成,已标记为拦截执行。`, + sender: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + metadata: { + orderCode, + orderId: existingOrder.id, + pickStatus: String(existingOrder.pick_status || 'none').trim(), + printStatus: String(existingOrder.print_status || 'none').trim(), + interceptStatus: String(existingOrder.intercept_status || 'none').trim(), + express, + }, + }); + } catch (error) { + ctx.logger.warn(`取消订单拦截通知发送失败: ${error.message}`); + } + } + async cancel(data) { const { ctx } = this; const info = this.getInfo(); const orderType = this.orderType[data.request.orderType]; switch (orderType.method) { case 'ORDER': - return this.success('取消订单成功'); + { + const orderCode = String(data?.request?.orderCode || '').trim(); + if (!orderCode) { + return this.fail('订单号不能为空'); + } + + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + const transaction = await ctx.model.transaction(); + try { + const existingOrder = await DeliveryModel.findOne({ + where: { + delivery_order_code: orderCode, + warehouse_id: info.warehouseId, + store_id: info.storeId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + if (!existingOrder) { + await transaction.rollback(); + return this.fail('未找到对应的订单'); + } + + const pickStatus = String(existingOrder.pick_status || 'none').trim(); + const printStatus = String(existingOrder.print_status || 'none').trim(); + + if (pickStatus !== 'none' || printStatus !== 'none') { + await existingOrder.update({ + intercept_status: 'intercepting', + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + await this.sendCancelInterceptNotice({ + orderCode, + existingOrder, + info, + }); + return this.fail('取消失败,已通知拦截执行'); + } + + await existingOrder.update({ + status: 'cancel', + outbound_status: 'fin', + step: 4, + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + return this.success('取消订单成功'); + } catch (error) { + try { + await transaction.rollback(); + } catch (rollbackError) { + ctx.logger.error('取消订单回滚失败', rollbackError); + } + ctx.logger.error(`取消订单失败: ${error.message}`); + return this.fail(error.message || '取消订单失败'); + } + } case 'RK': { const existingOrder = await ctx.model.EntryOrder.findOne({ diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 265f487..1b865ac 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -11,9 +11,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate'; + const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getPlatformList,recognizeLicensePlate'; const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate'; + const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getPlatformList,recognizeLicensePlate'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -418,8 +418,15 @@ class indexService extends MainService { return this.success('ok', { list, total: list.length, code: 200 }); } async getExpressList() { + const { service } = this; + const result = await service.systems.express.getExpressList(); + return this.success('ok', { data: result, code: 200 }); + } - return this.success('ok', { data: this.app.config.expressList, code: 200 }); + async getPlatformList() { + const { service } = this; + const result = await service.systems.platform.getPlatformList(); + return this.success('ok', { data: result, code: 200 }); } } module.exports = indexService; diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js index 47f2efc..c242284 100644 --- a/app/service/systemMethods/order/archiveOrder.js +++ b/app/service/systemMethods/order/archiveOrder.js @@ -6,64 +6,20 @@ class ArchiveOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getarchiveOrderlist'; - const _noNeedLog = 'getarchiveOrderlist'; - const _noNeedAuth = 'getarchiveOrderlist'; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取归档订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 归档订单列表。 + * @param {Object} data 请求体。 + * @param {Object} data.where 标准的查询条件对象,支持复杂查询。 + * @return {Promise} 列表与分页信息。 */ - async getarchiveOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); - if (!hasOutboundFilter) { - where.outbound_status = 'fin'; - } - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'outbound_status', - 'delivery_time', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultArchiveFilter: !hasOutboundFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('archiveOrder', data); } } diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index c7ddf4a..18751a5 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -1,224 +1,1065 @@ 'use strict'; const MainService = require('../../main'); +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const DEFAULT_PAGE_SIZE = 20; +const MAX_PAGE_SIZE = 200; +const FORBIDDEN_WAREHOUSE_FIELDS = new Set([ 'warehouse_id', 'warehouseId' ]); +const WAREHOUSE_FIELD_ERROR_MESSAGE = '订单工作台查询条件禁止传入 warehouse_id / warehouseId,请使用当前用户上下文的 store_id。'; + +const REVIEW_STATUS_STEP_MAP = Object.freeze({ + none: 0, + padding: 2, + running: 2, + fin: 1, + error: 3, +}); + +const REVIEW_ORDER_ALLOWED_FIELDS = Object.freeze([ 'ids' ]); +const BADGE_COUNT_OVER_LIMIT_VALUE = '99+'; +const ORDER_TABLE_TYPE_ALIASES = Object.freeze({ + current: 'current', + history: 'history', + dispatch: 'dispatch', + outsourced: 'outsourced', + order: 'current', + revieworder: 'current', + pendingorder: 'current', + outboundorder: 'current', + expectionorder: 'current', + archiveorder: 'history', + entrustorder: 'outsourced', + deliveryorder: 'dispatch', + deliveryexpectionorder: 'dispatch', +}); + +const MODULE_CONFIGS = Object.freeze({ + order: { + modelType: 'current', + defaultWhere: {}, + }, + reviewOrder: { + modelType: 'current', + defaultWhere: { + step: { + operator: 'eq', + value: 0, + }, + }, + }, + pendingOrder: { + modelType: 'current', + defaultWhere: { + outbound_status: { + operator: 'ne', + value: 'padding', + }, + step: { + operator: 'in', + value: [ 1, 2 ], + }, + }, + }, + outboundOrder: { + modelType: 'current', + defaultWhere: { + outbound_status: { + operator: 'in', + value: [ 'none', 'padding' ], + }, + step: { + operator: 'in', + value: [ 1, 2 ], + }, + }, + }, + expectionOrder: { + modelType: 'current', + defaultWhere: { + step: { + operator: 'eq', + value: 3, + }, + }, + }, + entrustOrder: { + modelType: 'outsourced', + defaultWhere: {}, + }, + deliveryOrder: { + modelType: 'dispatch', + defaultWhere: { + dispatch_lane: { + operator: 'eq', + value: 'm4', + }, + }, + }, + deliveryExpectionOrder: { + modelType: 'dispatch', + defaultWhere: { + dispatch_lane: { + operator: 'eq', + value: 'm5', + }, + }, + }, + archiveOrder: { + modelType: 'history', + defaultWhere: {}, + }, +}); + +/** + * 订单工作台系统方法基础能力。 + * 负责仓库上下文、分页规范、where 解析、模型选择与审核状态更新。 + */ class OrderBaseService extends MainService { - ensureWarehouseId(data = {}) { - const warehouseId = this.getWarehouseId(data); - if (!warehouseId) { - throw new Error('warehouse_id 不能为空'); - } - return warehouseId; - } + /** + * 获取当前请求对应的仓库ID。 + * @return {number|string|null} 仓库ID。 + */ + getWarehouseId() { + const { ctx } = this; + const warehouseId = ctx?.user?.store_id ?? null; - getWarehouseId(data = {}) { - const fromParam = Number(data.warehouse_id || data.warehouseId || 0); - const fromUser = Number(this.ctx.user?.store_id || 0); - return fromParam || fromUser; - } - - async getOrderModels(warehouseId) { - const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); - const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); - return { DeliveryModel, OrderItemsModel }; - } - - applyDateRange(where, field, start, end) { - const { Op } = this.app.Sequelize; - const range = {}; - - if (start) { - range[Op.gte] = this.normalizeDate(start, false); - } - if (end) { - range[Op.lte] = this.normalizeDate(end, true); - } - - if (Object.keys(range).length > 0) { - where[field] = range; - } - } - - getWhereCondition(whereData = {}, key) { - const condition = whereData[key]; - if (condition && typeof condition === 'object' && Object.prototype.hasOwnProperty.call(condition, 'value')) { - return condition; - } - return { - operator: 'eq', - value: condition, - }; - } - - getWhereValue(whereData = {}, key) { - return this.getWhereCondition(whereData, key).value; - } - - getWhereOperator(whereData = {}, key, defaultOperator = 'eq') { - const condition = this.getWhereCondition(whereData, key); - return String(condition.operator || defaultOperator).toLowerCase(); - } - - hasWhereValue(whereData = {}, key) { - const value = this.getWhereValue(whereData, key); - if (value === undefined || value === null) return false; - if (typeof value === 'string' && value.trim() === '') return false; - if (Array.isArray(value) && value.length === 0) return false; - return true; + return warehouseId === '' ? null : warehouseId; } /** - * 构建订单列表查询条件。 - * - * @param {Object} whereData where 过滤参数。 - * @param {number} warehouseId 仓库 ID。 - * @return {Object} Sequelize 查询条件。 + * 规范分页参数并限制 pageSize 上限。 + * @param {Object} pageParams 分页参数。 + * @return {{ page: number, pageSize: number }} 规范化结果。 */ - buildWhere(whereData = {}, warehouseId) { - const { Op } = this.app.Sequelize; - const where = { warehouse_id: warehouseId }; + normalizePagination(pageParams = {}) { + const requestParams = this.isPlainObject(pageParams) ? pageParams : {}; + const pageValue = requestParams.page ?? requestParams.currentPage ?? 1; + const pageSizeValue = requestParams.pageSize ?? requestParams.page_size ?? requestParams.size ?? DEFAULT_PAGE_SIZE; - const eqFields = [ - 'id', - 'store_id', - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'lock_status', - 'intercept_status', - 'step', - 'source_platform_code', - 'logistics_code', - 'warehouse_code', - 'order_type', + const page = Math.max(Number.parseInt(pageValue, 10) || 1, 1); + const pageSize = Math.min( + Math.max(Number.parseInt(pageSizeValue, 10) || DEFAULT_PAGE_SIZE, 1), + MAX_PAGE_SIZE + ); + + return { + page, + pageSize, + }; + } + + /** + * 规范化 where 入参,兼容简写值与标准 { operator, value } 结构。 + * @param {Object} whereInput where 条件对象。 + * @return {Object} 规范化后的 where 条件。 + */ + normalizeWhereInput(whereInput = {}) { + const sourceWhere = this.isPlainObject(whereInput && whereInput.where) + ? whereInput.where + : whereInput; + + if (!this.isPlainObject(sourceWhere)) { + return {}; + } + + const normalized = {}; + + for (const [ fieldKey, condition ] of Object.entries(sourceWhere)) { + if (FORBIDDEN_WAREHOUSE_FIELDS.has(fieldKey)) { + throw new Error(WAREHOUSE_FIELD_ERROR_MESSAGE); + } + + if (this.isPlainObject(condition)) { + const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ] + .some(key => Object.prototype.hasOwnProperty.call(condition, key)); + + if (hasStandardKeys) { + const normalizedCondition = { + ...condition, + }; + + if (!Object.prototype.hasOwnProperty.call(normalizedCondition, 'value') + && Object.prototype.hasOwnProperty.call(normalizedCondition, 'values')) { + normalizedCondition.value = normalizedCondition.values; + delete normalizedCondition.values; + } + + if (!Object.prototype.hasOwnProperty.call(normalizedCondition, 'operator') || !normalizedCondition.operator) { + normalizedCondition.operator = Array.isArray(normalizedCondition.value) ? 'in' : 'eq'; + } + + normalized[fieldKey] = normalizedCondition; + continue; + } + } + + normalized[fieldKey] = { + operator: Array.isArray(condition) ? 'in' : 'eq', + value: condition, + }; + } + + return normalized; + } + + /** + * 规范订单 ID 入参,兼容 ids、id、order_id、orderId 四种写法。 + * @param {Object} data 请求体。 + * @return {number[]} 订单 ID 列表。 + */ + normalizeOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawIds = requestData.ids; + const fallbackId = requestData.id !== undefined && requestData.id !== null && requestData.id !== '' + ? requestData.id + : requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '' + ? requestData.order_id + : requestData.orderId; + const sourceIds = []; + + if (Array.isArray(rawIds)) { + sourceIds.push(...rawIds); + } else if (typeof rawIds === 'string') { + sourceIds.push(...rawIds.split(',')); + } else if (rawIds !== undefined && rawIds !== null && rawIds !== '') { + sourceIds.push(rawIds); + } else if (requestData.id !== undefined && requestData.id !== null && requestData.id !== '') { + sourceIds.push(requestData.id); + } else if (requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '') { + sourceIds.push(requestData.order_id); + } else if (requestData.orderId !== undefined && requestData.orderId !== null && requestData.orderId !== '') { + sourceIds.push(requestData.orderId); + } + + const normalizedIds = []; + for (const value of sourceIds) { + const normalizedId = Number(String(value).trim()); + if (Number.isFinite(normalizedId) && normalizedId > 0) { + normalizedIds.push(normalizedId); + } + } + + if (normalizedIds.length === 0 && fallbackId !== undefined && fallbackId !== null && fallbackId !== '') { + const normalizedFallbackId = Number(String(fallbackId).trim()); + if (Number.isFinite(normalizedFallbackId) && normalizedFallbackId > 0) { + normalizedIds.push(normalizedFallbackId); + } + } + + return Array.from(new Set(normalizedIds)); + } + + /** + * 判断 where 条件是否可以安全合并到扁平对象。 + * @param {Object} condition Sequelize 条件对象。 + * @return {boolean} 是否可合并。 + */ + isMergeableWhereCondition(condition) { + if (!this.isPlainObject(condition)) { + return false; + } + + if (Object.getOwnPropertySymbols(condition).length > 0) { + return false; + } + + return Object.keys(condition).length === 1; + } + + /** + * 合并两个 where 对象,后者优先覆盖前者。 + * @param {Object} baseWhere 基础条件。 + * @param {Object} extraWhere 追加条件。 + * @return {Object} 合并后的条件。 + */ + mergeWhereObjects(baseWhere = {}, extraWhere = {}) { + return { + ...(this.isPlainObject(baseWhere) ? baseWhere : {}), + ...(this.isPlainObject(extraWhere) ? extraWhere : {}), + }; + } + + /** + * 获取模块配置。 + * @param {string} moduleName 模块名称。 + * @return {{ modelType: string, defaultWhere: Object }} 模块配置。 + */ + getModuleConfig(moduleName = 'order') { + return MODULE_CONFIGS[moduleName] || MODULE_CONFIGS.order; + } + + /** + * 获取模块默认筛选条件。 + * @param {string} moduleName 模块名称。 + * @return {Object} 默认筛选条件。 + */ + getDefaultWhere(moduleName = 'order') { + const config = this.getModuleConfig(moduleName); + return this.mergeWhereObjects({}, config.defaultWhere); + } + + /** + * 构造订单工作台角标缓存键。 + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 缓存键。 + */ + getBadgeCountCacheKey(warehouseId) { + return `systemMethods:order:badgeCount:${warehouseId}`; + } + + /** + * 将角标计数转换为前端展示值。 + * @param {number|string} count 订单数。 + * @return {number|string} 展示值。 + */ + formatBadgeCountValue(count) { + const normalizedCount = Number(count); + + if (!Number.isFinite(normalizedCount) || normalizedCount < 0) { + return 0; + } + + return normalizedCount > 99 ? BADGE_COUNT_OVER_LIMIT_VALUE : normalizedCount; + } + + /** + * 获取指定模块的角标展示值。 + * @param {string} moduleName 模块名称。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 角标展示值。 + */ + async getBadgeCountByModule(moduleName = 'order', warehouseId = this.getWarehouseId()) { + const actualWarehouseId = warehouseId ?? this.getWarehouseId(); + const model = await this.getOrderModel(moduleName, actualWarehouseId); + const queryWhere = this.buildWhere(this.getDefaultWhere(moduleName), actualWarehouseId); + const count = await model.count({ where: queryWhere }); + + return this.formatBadgeCountValue(count); + } + + /** + * 获取订单工作台对应的物理模型。 + * @param {string} moduleName 模块名称。 + * @param {number|string} [warehouseId] 仓库ID(保留兼容参数,实际以上下文 store_id 为准)。 + * @return {Promise} Sequelize 动态模型。 + */ + async getOrderModel(moduleName = 'order', warehouseId = null) { + const { ctx } = this; + const config = this.getModuleConfig(moduleName); + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const actualWarehouseId = contextWarehouseId; + + switch (config.modelType) { + case 'history': + return await ctx.model.OrderDeliveryFactory.getHistoryModel(actualWarehouseId); + case 'dispatch': + return await ctx.model.OrderDeliveryFactory.getDispatchModel(actualWarehouseId); + case 'outsourced': + return await ctx.model.OrderDeliveryFactory.getOutsourcedModel(actualWarehouseId); + case 'current': + default: + return await ctx.model.OrderDeliveryFactory.getCurrentModel(actualWarehouseId); + } + } + + /** + * 解析订单详情使用的表位类型。 + * @param {Object} data 请求体。 + * @return {string} 表位类型。 + */ + resolveOrderTableType(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const candidates = [ + requestData.tableType, + requestData.tablePosition, + requestData.type, + requestData.moduleName, ]; - for (const key of eqFields) { - if (!this.hasWhereValue(whereData, key)) { + for (const candidate of candidates) { + const normalizedCandidate = String(candidate ?? '').trim(); + if (!normalizedCandidate) { continue; } - const value = this.getWhereValue(whereData, key); - const operator = this.getWhereOperator(whereData, key); + const normalizedType = ORDER_TABLE_TYPE_ALIASES[normalizedCandidate.toLowerCase()]; + if (normalizedType) { + return normalizedType; + } - if (operator === 'in') { - where[key] = { - [Op.in]: Array.isArray(value) ? value : [ value ], - }; - } else if (operator === 'notin') { - where[key] = { - [Op.notIn]: Array.isArray(value) ? value : [ value ], - }; - } else if (operator === 'ne') { - where[key] = { - [Op.ne]: value, - }; - } else if (operator === 'like' || operator === 'contains') { - where[key] = { - [Op.like]: `%${value}%`, - }; - } else { - where[key] = value; + throw new Error(`不支持的订单表位类型: ${normalizedCandidate}`); + } + + return 'current'; + } + + /** + * 根据表位类型获取订单头模型。 + * @param {string} tableType 表位类型。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 订单头模型。 + */ + async getOrderModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) { + const { ctx } = this; + const contextWarehouseId = this.getWarehouseId(); + const normalizedTableType = this.resolveOrderTableType({ tableType }); + const actualWarehouseId = warehouseId ?? contextWarehouseId; + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== '' + && String(actualWarehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + switch (normalizedTableType) { + case 'history': + return await ctx.model.OrderDeliveryFactory.getHistoryModel(contextWarehouseId); + case 'dispatch': + return await ctx.model.OrderDeliveryFactory.getDispatchModel(contextWarehouseId); + case 'outsourced': + return await ctx.model.OrderDeliveryFactory.getOutsourcedModel(contextWarehouseId); + case 'current': + default: + return await ctx.model.OrderDeliveryFactory.getCurrentModel(contextWarehouseId); + } + } + + /** + * 根据表位类型获取订单商品模型。 + * @param {string} tableType 表位类型。 + * @param {number|string} [warehouseId] 仓库ID。 + * @return {Promise} 订单商品模型。 + */ + async getOrderItemsModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) { + const { ctx } = this; + const contextWarehouseId = this.getWarehouseId(); + const normalizedTableType = this.resolveOrderTableType({ tableType }); + const actualWarehouseId = warehouseId ?? contextWarehouseId; + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== '' + && String(actualWarehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory; + if (!orderItemsFactory) { + throw new Error('订单商品模型工厂不存在'); + } + + switch (normalizedTableType) { + case 'history': + return await orderItemsFactory.getHistoryModel(contextWarehouseId); + case 'dispatch': + return await orderItemsFactory.getDispatchModel(contextWarehouseId); + case 'outsourced': + return await orderItemsFactory.getOrCreateModel(contextWarehouseId, 'outsourced'); + case 'current': + default: + return await orderItemsFactory.getCurrentModel(contextWarehouseId); + } + } + + /** + * 查询订单关联运单信息。 + * @param {number|string} orderId 订单ID。 + * @return {Promise} 运单信息列表。 + */ + async getOrderExpressesByOrderId(orderId) { + const normalizedOrderId = Number(orderId || 0); + + if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) { + return []; + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return []; + } + + const rows = await orderExpressModel.findAll({ + where: { + order_id: normalizedOrderId, + }, + attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return (Array.isArray(rows) ? rows : []).map(row => ({ + waybill_code: String(row && row.waybill_code || '').trim(), + logistics_code: String(row && row.logistics_code || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id), + })); + } + + /** + * 归一化订单列表中的快递与系统名称字段。 + * @param {Object} orderRow 订单行。 + * @param {string[]} expressNumbers 快递号列表。 + * @return {Object} 归一化后的订单行。 + */ + normalizeOrderListRow(orderRow = {}, expressNumbers = []) { + const normalizedExpressNumbers = Array.isArray(expressNumbers) + ? Array.from(new Set(expressNumbers.map(item => String(item || '').trim()).filter(Boolean))) + : []; + + return { + ...orderRow, + sys_platform_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_platform_name') + ? (orderRow.sys_platform_name ?? null) + : null, + sys_logistics_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_logistics_name') + ? (orderRow.sys_logistics_name ?? null) + : null, + express_numbers: normalizedExpressNumbers, + waybill_codes: normalizedExpressNumbers, + }; + } + + /** + * 批量补齐订单列表的快递号信息。 + * @param {Object[]} list 订单列表。 + * @return {Promise} 补齐后的列表。 + */ + async attachOrderExpressNumbers(list = []) { + if (!Array.isArray(list) || list.length === 0) { + return Array.isArray(list) ? list : []; + } + + const orderIds = Array.from(new Set(list + .map(item => Number(item && item.id)) + .filter(value => Number.isFinite(value) && value > 0))); + + if (orderIds.length === 0) { + return list.map(item => this.normalizeOrderListRow(item, [])); + } + + const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress; + if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') { + return list.map(item => this.normalizeOrderListRow(item, [])); + } + + const { Op } = this.app.Sequelize; + const expressRows = await orderExpressModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + }, + attributes: [ 'id', 'order_id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id', 'platform_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const expressMap = new Map(); + if (Array.isArray(expressRows)) { + for (const row of expressRows) { + const orderId = Number(row && row.order_id); + const waybillCode = String(row && row.waybill_code || '').trim(); + + if (!Number.isFinite(orderId) || orderId <= 0 || !waybillCode) { + continue; + } + + const currentExpressNumbers = expressMap.get(orderId) || []; + currentExpressNumbers.push(waybillCode); + expressMap.set(orderId, currentExpressNumbers); } } - if (this.hasWhereValue(whereData, 'delivery_order_code')) { - const value = this.getWhereValue(whereData, 'delivery_order_code'); - const operator = this.getWhereOperator(whereData, 'delivery_order_code', 'like'); - if (operator === 'eq') { - where.delivery_order_code = value; - } else { - where.delivery_order_code = { [Op.like]: `%${value}%` }; + return list.map(item => { + const orderId = Number(item && item.id); + const orderExpressNumbers = Number.isFinite(orderId) && orderId > 0 + ? (expressMap.get(orderId) || []) + : []; + + return this.normalizeOrderListRow(item, orderExpressNumbers); + }); + } + + /** + * 构造列表排序参数。 + * @param {Object} sort 排序参数。 + * @param {string} [moduleName='order'] 模块名称。 + * @return {Array>} Sequelize order 配置。 + */ + buildListOrder(sort = {}, moduleName = 'order') { + const requestSort = this.isPlainObject(sort) ? sort : {}; + const sortField = requestSort.sortField || requestSort.field || requestSort.sort_by || requestSort.orderBy; + const sortOrder = String(requestSort.sortOrder || requestSort.order || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + const defaultSortField = moduleName === 'deliveryOrder' || moduleName === 'deliveryExpectionOrder' + ? 'delivery_time' + : 'updated_at'; + const allowedSortFields = new Set([ + 'id', + 'step', + 'status', + 'inspection_status', + 'dispatch_lane', + 'delivery_time', + 'create_at', + 'created_at', + 'updated_at', + 'delivery_order_code', + 'source_platform_code', + 'sync_status', + 'outbound_status', + ]); + const actualSortField = allowedSortFields.has(sortField) ? sortField : defaultSortField; + + return [ + [ actualSortField, sortOrder ], + [ 'id', 'DESC' ], + ]; + } + + /** + * 构造可直接传给 Sequelize 的 where 条件。 + * @param {Object} whereInput where 条件对象。 + * @param {number|string} warehouseId 仓库ID(保留兼容参数,实际以上下文 store_id 为准)。 + * @param {Object} [options] 解析选项。 + * @param {Object} [options.specialFieldMap] 特殊字段映射。 + * @return {Object} Sequelize where 条件。 + */ + buildWhere(whereInput = {}, warehouseId, options = {}) { + const { Sequelize } = this.app; + const specialFieldMap = this.isPlainObject(options.specialFieldMap) ? options.specialFieldMap : {}; + const contextWarehouseId = this.getWarehouseId(); + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + const normalizedWhere = this.normalizeWhereInput(whereInput); + const parsed = parseWhereConditions({ + where: normalizedWhere, + app: this.app, + specialFieldMap, + }); + + if (!parsed.ok) { + throw new Error(`where 参数解析失败: ${parsed.reason}`); + } + + const mergedConditions = []; + + if (contextWarehouseId !== null && contextWarehouseId !== undefined && contextWarehouseId !== '') { + mergedConditions.push({ + warehouse_id: contextWarehouseId, + }); + } + + if (Array.isArray(parsed.result.dynamicConditions)) { + mergedConditions.push(...parsed.result.dynamicConditions); + } + + if (this.isPlainObject(parsed.result.bucketConditions)) { + for (const bucketConditions of Object.values(parsed.result.bucketConditions)) { + if (Array.isArray(bucketConditions)) { + mergedConditions.push(...bucketConditions); + } } } - const deliveryOrderCodes = this.getWhereValue(whereData, 'delivery_order_codes'); - if (Array.isArray(deliveryOrderCodes) && deliveryOrderCodes.length > 0) { - where.delivery_order_code = { [Op.in]: deliveryOrderCodes }; + const flatWhere = {}; + const andConditions = []; + + for (const condition of mergedConditions) { + if (this.isMergeableWhereCondition(condition)) { + Object.assign(flatWhere, condition); + continue; + } + + andConditions.push(condition); } - if (this.hasWhereValue(whereData, 'logistics_name')) { - const value = this.getWhereValue(whereData, 'logistics_name'); - where.logistics_name = { [Op.like]: `%${value}%` }; + if (andConditions.length === 0) { + return flatWhere; } - if (this.hasWhereValue(whereData, 'buyer_nick')) { - const value = this.getWhereValue(whereData, 'buyer_nick'); - where.buyer_nick = { [Op.like]: `%${value}%` }; + if (Object.keys(flatWhere).length > 0) { + andConditions.unshift(flatWhere); } - if (this.hasWhereValue(whereData, 'mobile')) { - const value = this.getWhereValue(whereData, 'mobile'); - where.mobile = { [Op.like]: `%${value}%` }; + return { + [Sequelize.Op.and]: andConditions, + }; + } + + /** + * 查询模块列表。 + * @param {string} moduleName 模块名称。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async listByModule(moduleName = 'order', data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const contextWarehouseId = this.getWarehouseId(); + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const { where } = this.prepareWhereContext(requestData, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), where); + const queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { + specialFieldMap: { + quickWhere: { + bucket: 'quick', + }, + }, + }); + const model = await this.getOrderModel(moduleName, contextWarehouseId); + const order = this.buildListOrder(requestData.sort, moduleName); + const offset = (page - 1) * pageSize; + + const [ total, list ] = await Promise.all([ + model.count({ where: queryWhere }), + model.findAll({ + where: queryWhere, + limit: pageSize, + offset, + order, + raw: true, + }), + ]); + + const normalizedList = await this.attachOrderExpressNumbers(list); + + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + return { + list: normalizedList, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }; + } + + /** + * 查询订单详情。 + * @param {Object} data 请求体。 + * @return {Promise} 订单头、商品明细和运单信息。 + */ + async detail(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + const tableType = this.resolveOrderTableType(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); } - this.applyDateRange(where, 'create_at', this.getWhereValue(whereData, 'create_at_start'), this.getWhereValue(whereData, 'create_at_end')); - this.applyDateRange(where, 'place_order_time', this.getWhereValue(whereData, 'place_order_time_start'), this.getWhereValue(whereData, 'place_order_time_end')); - this.applyDateRange(where, 'pay_time', this.getWhereValue(whereData, 'pay_time_start'), this.getWhereValue(whereData, 'pay_time_end')); - this.applyDateRange(where, 'delivery_time', this.getWhereValue(whereData, 'delivery_time_start'), this.getWhereValue(whereData, 'delivery_time_end')); + if (orderIds.length !== 1) { + throw new Error('订单详情仅支持查询单个订单'); + } + + const orderId = orderIds[0]; + const orderModel = await this.getOrderModelByTableType(tableType, warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + raw: true, + }); + + if (!order) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId); + const orderItems = await orderItemsModel.findAll({ + where: { + order_id: orderId, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const expresses = await this.getOrderExpressesByOrderId(orderId); + const waybillCodes = Array.from(new Set(expresses + .map(item => String(item && item.waybill_code || '').trim()) + .filter(Boolean))); + + return { + order, + detail: order, + orderItems: Array.isArray(orderItems) ? orderItems : [], + items: Array.isArray(orderItems) ? orderItems : [], + expresses, + waybill_codes: waybillCodes, + }; + } + + /** + * 将审核状态映射为 step。 + * @param {string} reviewStatus 审核状态。 + * @return {number} 订单步骤。 + */ + resolveReviewStep(reviewStatus) { + const status = String(reviewStatus || '').trim(); + return REVIEW_STATUS_STEP_MAP[status] ?? 0; + } + + /** + * 规范审核提交入参中的订单ID列表,仅接受 ids。 + * @param {Object} data 请求体。 + * @return {number[]} 订单ID 列表。 + */ + normalizeReviewOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const unexpectedKeys = Object.keys(requestData).filter(key => !REVIEW_ORDER_ALLOWED_FIELDS.includes(key)); + + if (unexpectedKeys.length > 0) { + throw new Error('审核接口仅支持 ids 入参,不再支持 id/order_id/review_status/inspection_status/warehouse_id/warehouseId 等兼容字段'); + } + + const rawIds = requestData.ids; + const sourceIds = Array.isArray(rawIds) + ? rawIds + : typeof rawIds === 'string' + ? rawIds.split(',') + : rawIds !== undefined && rawIds !== null && rawIds !== '' + ? [ rawIds ] + : []; + + const normalizedIds = sourceIds + .map(value => Number(String(value).trim())) + .filter(value => Number.isFinite(value) && value > 0); + + return Array.from(new Set(normalizedIds)); + } + + /** + * 构建订单更新条件。 + * @param {number[]} orderIds 订单 ID 列表。 + * @param {number|string|null} warehouseId 仓库 ID(保留兼容参数,实际以上下文 store_id 为准)。 + * @return {Object} where 条件。 + */ + buildOrderWhere(orderIds = [], warehouseId = null) { + const { Op } = this.ctx.app.Sequelize; + const contextWarehouseId = this.getWarehouseId(); + const normalizedIds = Array.isArray(orderIds) + ? Array.from(new Set(orderIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0))) + : []; + + if (normalizedIds.length === 0) { + return {}; + } + + const where = { + id: normalizedIds.length === 1 ? normalizedIds[0] : { + [Op.in]: normalizedIds, + }, + }; + + if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + + if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '' + && String(warehouseId) !== String(contextWarehouseId)) { + throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。'); + } + + where.warehouse_id = contextWarehouseId; return where; } - parseDateTime(value, fieldName) { - if (!value) return null; - const d = value instanceof Date ? value : new Date(value); - if (Number.isNaN(d.getTime())) { - throw new Error(`${fieldName} 格式错误`); + /** + * 构建审核更新条件。 + * @param {number[]} orderIds 订单ID 列表。 + * @return {Object} where 条件。 + */ + buildReviewOrderWhere(orderIds = []) { + return this.buildOrderWhere(orderIds); + } + + /** + * 审核通过订单并进入待处理。 + * @param {Object} data 请求体。 + * @param {number[]|string} data.ids 批量订单ID。 + * @return {Promise} 更新后的订单信息。 + */ + async updateReviewOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeReviewOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); } - return d; - } - getPagination(pagination = {}) { - const page = Math.max(Number(pagination.page || 1), 1); - const pageSize = Math.min(Math.max(Number(pagination.pageSize || 20), 1), 200); - const offset = (page - 1) * pageSize; - return { page, pageSize, offset }; - } + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildReviewOrderWhere(orderIds); + const existingOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(existingOrders) || existingOrders.length !== orderIds.length) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const now = new Date(); + const updateValues = { + inspection_status: 'fin', + step: 1, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + inspection_status: order.inspection_status, + step: Number(order.step ?? 1), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; - buildPagination(page, pageSize, total) { return { - page, - pageSize, - total, - totalPages: Math.ceil(total / pageSize), - hasNext: page * pageSize < total, - hasPrevious: page > 1, + id: firstOrder.id, + inspection_status: firstOrder.inspection_status, + step: firstOrder.step, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), }; } - getOrderLocatorWhere(data = {}, warehouseId) { - const where = { warehouse_id: warehouseId }; + /** + * 更新订单审核态。 + * @param {Object} data 请求体。 + * @param {string} [targetInspectionStatus] 目标审核状态。 + * @param {Object} [options] 额外更新配置。 + * @param {Object} [options.extraUpdateValues] 附加更新字段。 + * @return {Promise} 更新后的订单信息。 + */ + async updateOrderInspectionState(data = {}, targetInspectionStatus = '', options = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + const inspectionStatus = String(targetInspectionStatus || requestData.review_status || requestData.inspection_status || '').trim(); + const extraUpdateValues = this.isPlainObject(options.extraUpdateValues) ? options.extraUpdateValues : {}; - if (data.id) { - where.id = data.id; - return where; + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); } - if (data.order_id) { - where.id = data.order_id; - return where; + if (!inspectionStatus) { + throw new Error('审核状态不能为空'); } - if (data.delivery_order_code) { - where.delivery_order_code = data.delivery_order_code; - return where; + const model = await this.getOrderModel('order', warehouseId); + const step = this.resolveReviewStep(inspectionStatus); + const now = new Date(); + const where = this.buildOrderWhere(orderIds, warehouseId); + const updateValues = { + inspection_status: inspectionStatus, + step, + updated_at: now, + ...extraUpdateValues, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); } - throw new Error('id 或 delivery_order_code 必填'); - } + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + inspection_status: order.inspection_status, + step: Number(order.step ?? step), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; - buildListData(rows, total, page, pageSize, extra = {}) { return { - list: rows, - pagination: this.buildPagination(page, pageSize, total), - ...extra, + id: firstOrder.id, + inspection_status: firstOrder.inspection_status, + step: firstOrder.step, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), }; } } diff --git a/app/service/systemMethods/order/deliveryExpectionOrder.js b/app/service/systemMethods/order/deliveryExpectionOrder.js new file mode 100644 index 0000000..5600de0 --- /dev/null +++ b/app/service/systemMethods/order/deliveryExpectionOrder.js @@ -0,0 +1,26 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class DeliveryExpectionOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,deliveryExpectionOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,deliveryExpectionOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 配送异常订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('deliveryExpectionOrder', data); + } + +} + +module.exports = DeliveryExpectionOrderService; diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index dbec4dc..2139260 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -6,66 +6,21 @@ class DeliveryOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getdeliveryOrderlist'; - const _noNeedLog = 'getdeliveryOrderlist'; - const _noNeedAuth = 'getdeliveryOrderlist'; + const _noNeedRight = 'list,deliveryOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,deliveryOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取已发货订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 配送订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - async getdeliveryOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); - if (!hasOutboundFilter) { - where.outbound_status = { [Op.ne]: 'none' }; - } - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'outbound_status', - 'delivery_time', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultOutboundFilter: !hasOutboundFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('deliveryOrder', data); } + } module.exports = DeliveryOrderService; diff --git a/app/service/systemMethods/order/entrustOrder.js b/app/service/systemMethods/order/entrustOrder.js new file mode 100644 index 0000000..9a05e48 --- /dev/null +++ b/app/service/systemMethods/order/entrustOrder.js @@ -0,0 +1,26 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class EntrustOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,entrustOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,entrustOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 委托外仓订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('entrustOrder', data); + } + +} + +module.exports = EntrustOrderService; diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js index a3044d4..3291afa 100644 --- a/app/service/systemMethods/order/expectionOrder.js +++ b/app/service/systemMethods/order/expectionOrder.js @@ -6,93 +6,21 @@ class ExpectionOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getexpectionOrderlist'; - const _noNeedLog = 'getexpectionOrderlist'; - const _noNeedAuth = 'getexpectionOrderlist'; + const _noNeedRight = 'list,expectionOrder'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list,expectionOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取异常订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 待处理异常订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - async getexpectionOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasExceptionFilter = [ - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'intercept_status', - ].some(key => this.hasWhereValue(whereData, key)); - - if (!hasExceptionFilter) { - where[Op.or] = [ - { status: 'error' }, - { post_status: 'error' }, - { storage_status: 'error' }, - { pick_status: 'error' }, - { pack_status: 'error' }, - { inspection_status: 'error' }, - { print_status: 'error' }, - { claim_status: 'error' }, - { outbound_status: 'error' }, - { intercept_status: 'exception' }, - ]; - } - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'post_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'outbound_status', - 'intercept_status', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultExceptionFilter: !hasExceptionFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('expectionOrder', data); } + } module.exports = ExpectionOrderService; diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 811dc4f..52af987 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -6,210 +6,73 @@ class OrderIndexService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder'; - const _noNeedLog = 'list,detail,listItems,stats,getreviewOrderlist'; - const _noNeedAuth = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder'; + const _noNeedRight = 'list,badgeCount,manualOutboundOrder,detail'; + const _noNeedLog = 'list,badgeCount,manualOutboundOrder,detail'; + const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,detail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } + /** + * 订单工作台总列表入口。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ async list(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - const { page, pageSize, offset } = this.getPagination(data.pagination); - - const result = await DeliveryModel.findAndCountAll({ - where, - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async detail(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const order = await DeliveryModel.findOne({ where, raw: true }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - - return this.success('ok', { - data: { order, items }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async listItems(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const order = await DeliveryModel.findOne({ - where, - attributes: [ 'id', 'delivery_order_code' ], - raw: true, - }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - - return this.success('ok', { - data: { order, items }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async stats(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Sequelize } = this.app; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const total = await DeliveryModel.count({ where }); - const byStatusRows = await DeliveryModel.findAll({ - where, - attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]], - group: [ 'status' ], - raw: true, - }); - const byOutboundRows = await DeliveryModel.findAll({ - where, - attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ]], - group: [ 'outbound_status' ], - raw: true, - }); - - return this.success('ok', { - data: { - total, - byStatus: byStatusRows, - byOutboundStatus: byOutboundRows, - }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async getreviewOrderlist(data = {}) { - return await this.ctx.service.systemMethods.order.reviewOrder.getreviewOrderlist(data); + return await this.listByModule('order', data); } /** - * 更新订单状态相关字段。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 更新结果。 + * 手动出库入口。 + * @param {Object} data 请求体。 + * @return {Promise} 迁移结果。 */ - async updateStatus(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const allowedFields = [ - 'status', - 'post_status', - 'storage_status', - 'pick_status', - 'pack_status', - 'inspection_status', - 'print_status', - 'claim_status', - 'outbound_status', - 'lock_status', - 'intercept_status', - 'step', - ]; - - const updateData = {}; - for (const key of allowedFields) { - if (data[key] !== undefined && data[key] !== null && data[key] !== '') { - updateData[key] = data[key]; - } - } - - if (data.delivery_time) { - updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time'); - } - - if (!updateData.delivery_time && updateData.outbound_status === 'fin') { - updateData.delivery_time = new Date(); - } - - if (Object.keys(updateData).length === 0) { - return this.fail('没有可更新字段', { code: 400 }); - } - - updateData.updated_at = new Date(); - - const [ affected ] = await DeliveryModel.update(updateData, { where }); - if (!affected) { - return this.fail('订单不存在或未更新', { code: 404 }); - } - - const order = await DeliveryModel.findOne({ where, raw: true }); - return this.success('更新成功', { data: order, code: 200 }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async manualOutboundOrder(data = {}) { + return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data); } - async updateDeliveryTime(data = {}) { - if (!data.delivery_time) { - return this.fail('delivery_time 必填', { code: 400 }); + /** + * 获取订单工作台 8 个标签页的角标计数。 + * 其中配送、异常与归档相关标签页直接返回 99+。 + * @return {Promise} 角标展示值对象。 + */ + async badgeCount() { + const warehouseId = this.getWarehouseId(); + + if (warehouseId === null || warehouseId === undefined || warehouseId === '') { + throw new Error('缺少当前用户仓库上下文 store_id'); } - const nextData = { ...data }; - if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') { - nextData.outbound_status = 'fin'; + const cacheKey = this.getBadgeCountCacheKey(warehouseId); + const cachedBadgeCount = await this.app.getCacheAsync(cacheKey); + + if (cachedBadgeCount && typeof cachedBadgeCount === 'object') { + return cachedBadgeCount; } - return await this.updateStatus(nextData); + const [ reviewOrder, pendingOrder, outboundOrder, expectionOrder, entrustOrder ] = await Promise.all([ + this.getBadgeCountByModule('reviewOrder', warehouseId), + this.getBadgeCountByModule('pendingOrder', warehouseId), + this.getBadgeCountByModule('outboundOrder', warehouseId), + this.getBadgeCountByModule('expectionOrder', warehouseId), + this.getBadgeCountByModule('entrustOrder', warehouseId), + ]); + + const badgeCount = { + reviewOrder, + pendingOrder, + outboundOrder, + expectionOrder, + entrustOrder, + deliveryOrder: '99+', + deliveryExpectionOrder: '99+', + archiveOrder: '99+', + }; + + await this.app.setCacheAsync(cacheKey, badgeCount, 30); + + return badgeCount; } - async reviewOrder(data = {}) { - return await this.ctx.service.systemMethods.order.reviewOrder.reviewOrder(data); - } } module.exports = OrderIndexService; diff --git a/app/service/systemMethods/order/outboundOrder.js b/app/service/systemMethods/order/outboundOrder.js new file mode 100644 index 0000000..fcc8c18 --- /dev/null +++ b/app/service/systemMethods/order/outboundOrder.js @@ -0,0 +1,34 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +class OutboundOrderService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,outboundOrder,manualOutboundOrder'; + const _noNeedLog = 'list,manualOutboundOrder'; + const _noNeedAuth = 'list,outboundOrder,manualOutboundOrder'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 待出库订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 + */ + async list(data = {}) { + return await this.listByModule('outboundOrder', data); + } + + /** + * 手动出库入口。 + * @param {Object} data 请求体。 + * @return {Promise} 迁移结果。 + */ + async manualOutboundOrder(data = {}) { + return await this.ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery(data); + } +} + +module.exports = OutboundOrderService; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 5f59478..8cdc96b 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -2,75 +2,293 @@ const OrderBaseService = require('./base'); +const PENDING_OUTBOUND_STATUS = 'padding'; +const PENDING_CANCEL_STATUS = 'cancel'; +const PENDING_CANCEL_STEP = 9; +const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]); +const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]); + class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getpendingOrderlist'; - const _noNeedLog = 'getpendingOrderlist'; - const _noNeedAuth = 'getpendingOrderlist'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 获取待处理订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 + * 待处理订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - async getpendingOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); + async list(data = {}) { + return await this.listByModule('pendingOrder', data); + } - const hasStatusFilter = this.hasWhereValue(whereData, 'status'); - const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status'); + /** + * 将待处理订单反审回待审核状态。 + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息。 + */ + async reverseReviewOrder(data = {}) { + return await this.updateOrderInspectionState(data, 'none'); + } - if (!hasStatusFilter) { - where.status = { [Op.in]: [ 'pedding', 'created' ] }; - } - if (!hasOutboundFilter) { - where.outbound_status = 'none'; - } + /** + * 将待处理订单批量标记为待出库。 + * @param {Object} data 请求体。 + * @param {number[]} data.ids 订单ID 数组。 + * @return {Promise} 更新后的订单信息。 + */ + async markPendingOutboundOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizePendingOutboundOrderIds(requestData); - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'outbound_status', - 'inspection_status', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultPendingStatusFilter: !hasStatusFilter, - defaultPendingOutboundFilter: !hasOutboundFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); } + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + const existingOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(existingOrders) || existingOrders.length === 0) { + return this.success('取消成功', { + updated_count: 0, + ids: [], + }); + } + + if (existingOrders.length !== orderIds.length) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const now = new Date(); + const updateValues = { + outbound_status: PENDING_OUTBOUND_STATUS, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + outbound_status: order.outbound_status, + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; + + return { + id: firstOrder.id, + outbound_status: firstOrder.outbound_status, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), + }; + } + + /** + * 将待处理订单取消,并关闭到已取消状态。 + * 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。 + * @param {Object} data 请求体。 + * @param {number[]} data.ids 订单ID 数组。 + * @return {Promise} 更新后的订单信息。 + */ + async cancelOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizePendingCancelOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + const model = await this.getOrderModel('order', warehouseId); + const where = this.buildOrderWhere(orderIds, warehouseId); + const existingOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(existingOrders) || existingOrders.length === 0) { + return this.success('取消成功', { + updated_count: 0, + ids: [], + }); + } + + if (existingOrders.length !== orderIds.length) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order)); + if (nonCancelableOrder) { + throw new Error('订单当前状态不允许取消'); + } + + const now = new Date(); + const updateValues = { + status: PENDING_CANCEL_STATUS, + step: PENDING_CANCEL_STEP, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + status: order.status, + step: Number(order.step ?? PENDING_CANCEL_STEP), + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; + + return { + id: firstOrder.id, + status: firstOrder.status, + step: firstOrder.step, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), + }; + } + + /** + * 规范待处理出库订单ID入参,仅接受 ids 数组且元素必须为正整数。 + * @param {Object} data 请求体。 + * @return {number[]} 订单ID 数组。 + */ + normalizePendingOutboundOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids'); + + if (unexpectedKeys.length > 0) { + throw new Error('待处理出库接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段'); + } + + if (!Array.isArray(requestData.ids)) { + throw new Error('待处理出库接口仅支持 ids 数组入参'); + } + + const normalizedIds = requestData.ids.map(value => { + if (!Number.isInteger(value) || value <= 0) { + throw new Error('ids 仅支持正整数数组'); + } + + return value; + }); + + return Array.from(new Set(normalizedIds)); + } + + /** + * 规范待处理取消订单ID入参,仅接受 ids 数组且元素必须为正整数。 + * @param {Object} data 请求体。 + * @return {number[]} 订单ID 数组。 + */ + normalizePendingCancelOrderIds(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids'); + + if (unexpectedKeys.length > 0) { + throw new Error('待处理取消接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段'); + } + + if (!Array.isArray(requestData.ids)) { + throw new Error('待处理取消接口仅支持 ids 数组入参'); + } + + const normalizedIds = requestData.ids.map(value => { + if (!Number.isInteger(value) || value <= 0) { + throw new Error('ids 仅支持正整数数组'); + } + + return value; + }); + + return Array.from(new Set(normalizedIds)); + } + + /** + * 判断订单是否允许从待处理模块取消。 + * 仅允许处于待审核、待处理、待处理异常语义的订单取消。 + * @param {Object} order 订单记录。 + * @return {boolean} 是否允许取消。 + */ + isCancelablePendingOrder(order = {}) { + const step = Number(order.step); + const status = String(order.status || '').trim().toLowerCase(); + const outboundStatus = String(order.outbound_status || '').trim(); + + if (status === PENDING_CANCEL_STATUS) { + return false; + } + + if (!PENDING_CANCEL_ALLOWED_STEPS.has(step)) { + return false; + } + + if (PENDING_CANCEL_PENDING_STEPS.has(step) && outboundStatus === PENDING_OUTBOUND_STATUS) { + return false; + } + + return true; } } diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js index 7aec438..40bb1de 100644 --- a/app/service/systemMethods/order/reviewOrder.js +++ b/app/service/systemMethods/order/reviewOrder.js @@ -6,139 +6,28 @@ class ReviewOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getreviewOrderlist,reviewOrder'; - const _noNeedLog = 'getreviewOrderlist'; - const _noNeedAuth = 'getreviewOrderlist,reviewOrder'; + const _noNeedRight = 'list,reviewOrder,'; + const _noNeedLog = 'list,reviewOrder'; + const _noNeedAuth = 'list,reviewOrder'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 将审核状态映射为订单步骤。 - * - * @param {string} reviewStatus 审核状态。 - * @return {number} 订单步骤值。 + * 待审核订单列表。 + * @param {Object} data 请求体。 + * @return {Promise} 列表与分页信息。 */ - mapReviewStatusToStep(reviewStatus) { - const status = String(reviewStatus || 'none').trim(); - - if (status === 'fin') { - return 1; - } - if (status === 'running' || status === 'padding') { - return 2; - } - if (status === 'error') { - return 3; - } - return 0; - } - - /** - * 获取待审核订单列表。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 查询结果。 - */ - async getreviewOrderlist(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { Op } = this.app.Sequelize; - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - - const hasInspectionFilter = this.hasWhereValue(whereData, 'inspection_status'); - if (!hasInspectionFilter) { - where.inspection_status = { [Op.ne]: 'none' }; - } - - if (this.hasWhereValue(whereData, 'operator_name')) { - const operatorName = this.getWhereValue(whereData, 'operator_name'); - where.operator_name = { [Op.like]: `%${operatorName}%` }; - } - - this.applyDateRange( - where, - 'operate_time', - this.getWhereValue(whereData, 'operate_time_start'), - this.getWhereValue(whereData, 'operate_time_end') - ); - - const { page, pageSize, offset } = this.getPagination(data.pagination); - const result = await DeliveryModel.findAndCountAll({ - where, - attributes: [ - 'id', - 'delivery_order_code', - 'status', - 'step', - 'inspection_status', - 'operator_name', - 'operate_time', - 'updated_at', - 'store_id', - 'warehouse_id', - 'buyer_nick', - 'logistics_name', - ], - offset, - limit: pageSize, - order: [[ 'operate_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize, { - queryInfo: { - defaultInspectionFilter: !hasInspectionFilter, - }, - }), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + async list(data = {}) { + return await this.listByModule('reviewOrder', data); } /** * 更新订单审核状态。 - * - * @param {Object} data 请求参数。 - * @return {Promise} 更新结果。 + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息。 */ async reviewOrder(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const reviewStatus = String( - data.review_status ?? data.reviewStatus ?? data.inspection_status ?? 'fin' - ).trim(); - const allowedReviewStatus = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); - if (!allowedReviewStatus.has(reviewStatus)) { - return this.fail('review_status 参数不合法', { code: 400 }); - } - - const updateData = { - inspection_status: reviewStatus, - step: this.mapReviewStatusToStep(reviewStatus), - operator_name: data.operator_name || this.ctx.user?.real_name || this.ctx.user?.username || null, - operate_time: data.operate_time ? this.parseDateTime(data.operate_time, 'operate_time') : new Date(), - updated_at: new Date(), - }; - - const [ affected ] = await DeliveryModel.update(updateData, { where }); - if (!affected) { - return this.fail('订单不存在或未更新', { code: 404 }); - } - - const order = await DeliveryModel.findOne({ where, raw: true }); - return this.success('审核成功', { data: order, code: 200 }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } + return await this.updateReviewOrder(data); } } diff --git a/app/service/systemMethods/order/storageAllocation.js b/app/service/systemMethods/order/storageAllocation.js new file mode 100644 index 0000000..ea2a32b --- /dev/null +++ b/app/service/systemMethods/order/storageAllocation.js @@ -0,0 +1,47 @@ +'use strict'; + +const OrderBaseService = require('./base'); + +/** + * 系统方法层:订单储位分配入口。 + * 仅负责参数归一化与调用底层公共 service。 + */ +class StorageAllocationService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'allocateStorage'; + const _noNeedLog = 'allocateStorage'; + const _noNeedAuth = 'allocateStorage'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 批量分配订单储位。 + * + * @param {Object} data 请求体。 + * @return {Promise} 统一 success 包装。 + */ + async allocateStorage(data = {}) { + const { service } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const normalizedData = { + allow_storage_location: requestData.allow_storage_location + ?? requestData.allowStorageLocation + ?? requestData.is_allow_storage + ?? requestData.isAllowStorage, + order_ids: requestData.order_ids + ?? requestData.orderIds + ?? requestData.ids + ?? requestData.order_id + ?? requestData.orderId + ?? requestData.id, + warehouse_id: requestData.warehouse_id ?? requestData.warehouseId, + }; + + const result = await service.systems.orderStorageAllocation.allocateStorage(normalizedData); + return this.success('ok', result); + } +} + +module.exports = StorageAllocationService; \ No newline at end of file diff --git a/app/service/systemMethods/storage/expiry.js b/app/service/systemMethods/storage/expiry.js new file mode 100644 index 0000000..631ed48 --- /dev/null +++ b/app/service/systemMethods/storage/expiry.js @@ -0,0 +1,61 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.expiry(库存有效期列表包装层)。 + * 职责:拆解 where 与分页参数,调用库存有效期业务服务并统一包装响应。 + */ +class StorageExpiryMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询库存有效期预警列表。 + * + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 统一 success 包装响应 + */ + async list(data = {}) { + const { service } = this; + const { pagination } = data; + const { where } = this.prepareWhereContext(data, { + specialFieldMap: { + item_code: { + bucket: 'stock', + }, + goods_code: { + bucket: 'stock', + }, + item_name: { + bucket: 'stock', + }, + sku_property: { + bucket: 'stock', + }, + stock_unit: { + bucket: 'stock', + }, + is_shelf_life_mgmt: { + bucket: 'stock', + field: 'is_shelf_life_mgmt', + }, + remaining_threshold_days: { + bucket: 'stock', + }, + }, + }); + const result = await service.systems.storage.expiry.list(where, pagination); + return this.success('ok', result); + } +} + +module.exports = StorageExpiryMethodService; diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index b3f0df8..1d7acad 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -82,8 +82,8 @@ class InventoryMethodService extends MainService { async list(data = {}) { const { service } = this; const { pagination, sort, group_by_batch } = data; - const { where } = this.prepareWhereContext(data); - const result = await service.systems.storage.inventory.getInventoryList(where, pagination, sort, group_by_batch); + this.prepareWhereContext(data); + const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch); return this.success('ok', result); } } diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js deleted file mode 100644 index bf2f610..0000000 --- a/app/service/systemMethods/storage/stockout.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -const OrderBaseService = require('../order/base'); - -/** - * 系统方法层:storage.stockout(非订单出库单接口包装层)。 - */ -class StorageStockoutService extends OrderBaseService { - constructor(ctx) { - super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,toOrder,listItems'; - const _noNeedLog = 'list,toOrder,listItems'; - const _noNeedAuth = 'list,toOrder,listItems'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - async list(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel } = await this.getOrderModels(warehouseId); - this.prepareWhereContext(data); - const whereData = this.ctx.where || {}; - const where = this.buildWhere(whereData, warehouseId); - // 默认只查询订单类型为 STOCKOUT 的出库单 - if (!whereData.order_type && !where.order_type) { - where.order_type = 'STOCKOUT'; - } - const { page, pageSize, offset } = this.getPagination(data.pagination); - - const result = await DeliveryModel.findAndCountAll({ - where, - offset, - limit: pageSize, - order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], - raw: true, - }); - - return this.success('ok', { - data: this.buildListData(result.rows, result.count, page, pageSize), - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } - - async toOrder() { - return this.fail('占位接口,暂未开放', { code: 405, placeholder: true }); - } - - async listItems(data = {}) { - try { - const warehouseId = this.ensureWarehouseId(data); - const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); - const where = this.getOrderLocatorWhere(data, warehouseId); - - const order = await DeliveryModel.findOne({ - where, - attributes: [ 'id', 'delivery_order_code' ], - raw: true, - }); - if (!order) { - return this.fail('订单不存在', { code: 404 }); - } - - const items = await OrderItemsModel.findAll({ - where: { order_id: order.id }, - order: [[ 'id', 'ASC' ]], - raw: true, - }); - - return this.success('ok', { - data: { order, items }, - code: 200, - }); - } catch (error) { - return this.fail(error.message, { code: 500 }); - } - } -} - -module.exports = StorageStockoutService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 75dfbfa..f6239e5 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1,5 +1,6 @@ 'use strict'; const Service = require('egg').Service; +const { normalizeWarehouseShardId } = require('../../lib/warehouse_shard_guard'); const DELIVERY_ORDER_STEP = Object.freeze({ PENDING_REVIEW: 0, @@ -11,7 +12,174 @@ const DELIVERY_ORDER_STEP = Object.freeze({ CLOSED: 9, }); +const DEFAULT_STORE_SUBJECT_CONFIG = Object.freeze({ + max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', +}); + +const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600; + class DeliveryOrderService extends Service { + getStoreSubjectConfigCacheKey(storeId) { + return `delivery_order:store:${Number(storeId || 0)}:subject_config`; + } + + normalizeStoreSubjectConfig(rawValue) { + const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store); + if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') { + return storeModel.normalizeSubjectConfig(rawValue); + } + + return { + ...DEFAULT_STORE_SUBJECT_CONFIG, + ...(rawValue && typeof rawValue === 'object' && !Array.isArray(rawValue) ? rawValue : {}), + }; + } + + async getStoreSubjectConfig(storeId) { + const normalizedStoreId = Number(storeId || 0); + if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0) { + return this.normalizeStoreSubjectConfig(null); + } + + const cacheKey = this.getStoreSubjectConfigCacheKey(normalizedStoreId); + if (this.app && typeof this.app.getCacheAsync === 'function') { + try { + const cachedValue = await this.app.getCacheAsync(cacheKey); + if (cachedValue && typeof cachedValue === 'object') { + return this.normalizeStoreSubjectConfig(cachedValue); + } + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] read cache failed: %s', error.message); + } + } + + const storeModel = (this.app.model && this.app.model.Store) || (this.ctx.model && this.ctx.model.Store); + if (!storeModel || typeof storeModel.findByPk !== 'function') { + return this.normalizeStoreSubjectConfig(null); + } + + try { + const store = await storeModel.findByPk(normalizedStoreId, { + attributes: [ 'id', 'subject_config' ], + }); + const normalizedConfig = this.normalizeStoreSubjectConfig(store && store.subject_config); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(cacheKey, normalizedConfig, STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS); + } + + return normalizedConfig; + } catch (error) { + this.ctx.logger.warn('[DeliveryOrderService.getStoreSubjectConfig] load subject_config failed: %s', error.message); + return this.normalizeStoreSubjectConfig(null); + } + } + + findCodeOption(list, code) { + const normalizedCode = String(code || '').trim(); + if (!normalizedCode || !Array.isArray(list)) { + return null; + } + + return list.find(item => item && String(item.code || item.value || '').trim() === normalizedCode) || null; + } + + getOptionName(option) { + if (!option || typeof option !== 'object') { + return ''; + } + + return String(option.name || option.label || option.code || option.value || '').trim(); + } + + async resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, info = {}) { + const platformList = await this.ctx.service.systems.platform.getPlatformList(); + const externalCode = String(sourcePlatformCode || '').trim(); + const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_platform_code || '').trim(); + const matchedPlatform = this.findCodeOption(platformList, externalCode); + + if (matchedPlatform) { + return { + sysPlatformCode: String(matchedPlatform.code || matchedPlatform.value || externalCode).trim(), + sysPlatformName: this.getOptionName(matchedPlatform), + }; + } + + const fallbackPlatform = this.findCodeOption(platformList, defaultCode); + if (fallbackPlatform) { + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid platform code fallback to store default', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + sourcePlatformCode: externalCode, + defaultPlatformCode: defaultCode, + }); + + return { + sysPlatformCode: String(fallbackPlatform.code || fallbackPlatform.value || defaultCode).trim(), + sysPlatformName: this.getOptionName(fallbackPlatform), + }; + } + + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] platform default not found in platform service list', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + sourcePlatformCode: externalCode, + defaultPlatformCode: defaultCode, + }); + + return { + sysPlatformCode: defaultCode || externalCode, + sysPlatformName: '', + }; + } + + async resolveExpressSnapshot(logisticsCode, storeSubjectConfig, info = {}) { + const expressList = await this.ctx.service.systems.express.getExpressList(); + const externalCode = String(logisticsCode || '').trim(); + const defaultCode = String(storeSubjectConfig && storeSubjectConfig.default_express_code || '').trim(); + const matchedExpress = this.findCodeOption(expressList, externalCode); + + if (matchedExpress) { + return { + sysLogisticsCode: String(matchedExpress.code || matchedExpress.value || externalCode).trim(), + sysLogisticsName: this.getOptionName(matchedExpress), + }; + } + + const fallbackExpress = this.findCodeOption(expressList, defaultCode); + if (fallbackExpress) { + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] invalid logistics code fallback to store default', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + defaultExpressCode: defaultCode, + }); + + return { + sysLogisticsCode: String(fallbackExpress.code || fallbackExpress.value || defaultCode).trim(), + sysLogisticsName: this.getOptionName(fallbackExpress), + }; + } + + this.ctx.logger.warn('[DeliveryOrderService.prepareOrderData] express default not found in express service list', { + deliveryOrderCode: info.deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + logisticsCode: externalCode, + defaultExpressCode: defaultCode, + }); + + return { + sysLogisticsCode: defaultCode || externalCode, + sysLogisticsName: '', + }; + } + /** * 创建发货单。 * @@ -21,14 +189,18 @@ class DeliveryOrderService extends Service { */ async addOrder(data, info) { const { ctx } = this; - if (!info.warehouseId) { + let warehouseIdStr; + try { + warehouseIdStr = normalizeWarehouseShardId(info.warehouseId); + } catch (e) { return { success: false, - message: '订单创建失败: 非法参数', + message: `订单创建失败: ${e.message}`, data: null, }; } - const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId); + info = { ...info, warehouseId: warehouseIdStr }; + const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseIdStr); const { deliveryOrder, orderLines } = data.request; // 开启事务 @@ -189,12 +361,12 @@ class DeliveryOrderService extends Service { : DELIVERY_ORDER_STEP.PENDING_REVIEW; } - /** - * 生成订单结构哈希值。 - * - * @param {Object} itemsInfo 订单明细信息。 - * @return {string} 结构哈希值。 - */ + /** + * 生成订单结构哈希值。 + * + * @param {Object} itemsInfo 订单明细信息。 + * @return {string} 结构哈希值。 + */ generateItemsHash(itemsInfo) { const crypto = require('crypto'); @@ -239,7 +411,7 @@ class DeliveryOrderService extends Service { * @return {Promise} 可入库的订单数据。 */ async prepareOrderData(deliveryOrder, info, step = DELIVERY_ORDER_STEP.PENDING_REVIEW) { - const { ctx, service } = this; + const { service } = this; const { deliveryOrderCode, preDeliveryOrderCode, @@ -273,34 +445,17 @@ class DeliveryOrderService extends Service { receiverInfo, } = deliveryOrder; - let platformCode = sourcePlatformCode; - let platformName = sourcePlatformName; - - try { - // 验证平台代码是否存在 - const platformInfo = await service.systems.platform.checkPlatformExists( - sourcePlatformCode, - info.warehouseId - ); - - if (platformInfo) { - // 平台存在,使用数据库中的平台信息 - platformCode = platformInfo.code; - platformName = platformInfo.name; - - ctx.logger.info(`平台验证通过: ${sourcePlatformCode} -> ${platformCode} (${platformName})`); - } else { - // 平台不存在,抛出错误 - throw new Error(`平台代码 ${sourcePlatformCode} 在仓库 ${info.warehouseId} 中不存在`); - } - } catch (error) { - ctx.logger.error(`平台验证失败: ${error.message}`, { - platformCode: sourcePlatformCode, - warehouseId: info.warehouseId, - deliveryOrderCode, - }); - throw error; // 抛出错误,让上层捕获 - } + const storeSubjectConfig = await this.getStoreSubjectConfig(info.storeId); + const platformSnapshot = await this.resolvePlatformSnapshot(sourcePlatformCode, storeSubjectConfig, { + deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + }); + const expressSnapshot = await this.resolveExpressSnapshot(logisticsCode, storeSubjectConfig, { + deliveryOrderCode, + warehouseId: info.warehouseId, + storeId: info.storeId, + }); return { delivery_order_code: deliveryOrderCode, @@ -309,9 +464,10 @@ class DeliveryOrderService extends Service { order_type: orderType, warehouse_code: warehouseCode, order_flag: orderFlag || '', - // 使用验证后的平台信息 - source_platform_code: platformCode, - source_platform_name: platformName, + source_platform_code: sourcePlatformCode || '', + source_platform_name: sourcePlatformName || '', + sys_platform_code: platformSnapshot.sysPlatformCode, + sys_platform_name: platformSnapshot.sysPlatformName, create_at: createTime ? new Date(createTime) : new Date(), place_order_time: placeOrderTime ? new Date(placeOrderTime) : null, pay_time: payTime ? new Date(payTime) : null, @@ -327,8 +483,10 @@ class DeliveryOrderService extends Service { freight: freight ? parseFloat(freight) : 0, ar_amount: arAmount ? parseFloat(arAmount) : 0, got_amount: gotAmount ? parseFloat(gotAmount) : 0, - logistics_code: logisticsCode, - logistics_name: logisticsName, + logistics_code: logisticsCode || '', + logistics_name: logisticsName || '', + sys_logistics_code: expressSnapshot.sysLogisticsCode, + sys_logistics_name: expressSnapshot.sysLogisticsName, express_code: expressCode || '', logistics_area_code: logisticsAreaCode || '', is_urgency: isUrgency || 'N', @@ -494,7 +652,7 @@ class DeliveryOrderService extends Service { ext_code: line.extCode || '', inventory_type: line.inventoryType || '', item_code: line.itemCode || '', - item_id: line.itemId || null, + item_id: itemId, item_name: line.itemName || '', order_line_no: line.orderLineNo || `${i + 1}`, owner_code: line.ownerCode || '', @@ -504,6 +662,8 @@ class DeliveryOrderService extends Service { extend_props: line.extendProps ? (typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps)) : null, + stock_id: stockId, + item_snapshot: this.buildOrderItemSnapshot(wms_stock, line), // 可选:记录重量信息到明细 item_weight: stockWeightMap.get(stockId) || 0, }); @@ -585,6 +745,31 @@ class DeliveryOrderService extends Service { }; } + buildOrderItemSnapshot(stockRecord = {}, line = {}) { + return { + id: Number(stockRecord.id || 0) || null, + stock_id: Number(stockRecord.stock_id || 0) || null, + item_code: String(stockRecord.item_code || line.itemCode || '').trim(), + item_name: String(stockRecord.item_name || line.itemName || '').trim(), + goods_code: String(stockRecord.goods_code || '').trim(), + sku_property: String(stockRecord.sku_property || '').trim(), + barcode: String(stockRecord.barcode || '').trim(), + brand_name: String(stockRecord.brand_name || '').trim(), + category_id: Number(stockRecord.category_id || 0) || null, + category_name: String(stockRecord.category_name || '').trim(), + item_type: String(stockRecord.item_type || '').trim(), + stock_unit: String(stockRecord.stock_unit || '').trim(), + inventory_type: String(line.inventoryType || '').trim(), + retail_price: this.safeParseFloat(stockRecord.retail_price, this.safeParseFloat(line.retailPrice, 0)), + gross_weight: this.safeParseFloat(stockRecord.gross_weight, 0), + net_weight: this.safeParseFloat(stockRecord.net_weight, 0), + length: this.safeParseFloat(stockRecord.length, 0), + width: this.safeParseFloat(stockRecord.width, 0), + height: this.safeParseFloat(stockRecord.height, 0), + volume: this.safeParseFloat(stockRecord.volume, 0), + }; + } + // 添加工具方法 safeParseFloat(value, defaultValue = 0) { if (value === null || value === undefined) return defaultValue; diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js index cad0bd6..ac26405 100644 --- a/app/service/systems/excel.js +++ b/app/service/systems/excel.js @@ -521,7 +521,7 @@ class ExcelService extends Service { }); await fs.promises.mkdir(path.dirname(resolvedFilePath), { recursive: true }); - await fs.promises.writeFile(resolvedFilePath, buffer); + await this.writeAtomicBufferFile(resolvedFilePath, buffer); return { filePath: resolvedFilePath, @@ -530,6 +530,30 @@ class ExcelService extends Service { }; } + async writeAtomicBufferFile(targetPath, buffer) { + const directory = path.dirname(targetPath); + const tempPath = path.join( + directory, + `.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp` + ); + + await fs.promises.writeFile(tempPath, buffer); + + try { + await fs.promises.rename(tempPath, targetPath); + } catch (error) { + if (error && (error.code === 'EEXIST' || error.code === 'EPERM' || error.code === 'EBUSY')) { + await fs.promises.rm(targetPath, { force: true }); + await fs.promises.rename(tempPath, targetPath); + return; + } + + throw error; + } finally { + await fs.promises.rm(tempPath, { force: true }).catch(() => {}); + } + } + sanitizeFilename(filename = 'export.xlsx', fallbackExt = '.xlsx') { const normalizedName = String(filename || '').trim() || `export${fallbackExt}`; const rawExt = path.extname(normalizedName); diff --git a/app/service/systems/express.js b/app/service/systems/express.js new file mode 100644 index 0000000..372dd00 --- /dev/null +++ b/app/service/systems/express.js @@ -0,0 +1,69 @@ +'use strict'; + +const { Service } = require('egg'); + +const DEFAULT_CACHE_TTL_SECONDS = 600; + +class ExpressService extends Service { + getExpressListCacheKey() { + return 'express:list'; + } + + normalizeExpressRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + return { + code, + name: String(row.name || '').trim(), + value: code, + label: String(row.name || code).trim(), + }; + } + + async loadExpressListFromDatabase() { + const rows = await this.ctx.model.Express.findAll({ + attributes: [ 'code', 'name' ], + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(row => this.normalizeExpressRow(row)) + .filter(Boolean); + } + + async getExpressList() { + const cacheKey = this.getExpressListCacheKey(); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + + const expressList = await this.loadExpressListFromDatabase(); + await this.app.setCacheAsync(cacheKey, expressList, DEFAULT_CACHE_TTL_SECONDS); + + return expressList; + } catch (error) { + this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', { + error: error.message, + stack: error.stack, + }); + throw error; + } + } +} + +module.exports = ExpressService; \ No newline at end of file diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 7ac776a..fe6ba7c 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -24,6 +24,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed', + 'order_cancel_intercepted', 'store_warehouse_print_quantity_adjusted', ]); const DRIVER_TYPE_ALIASES = Object.freeze({ @@ -586,6 +587,8 @@ class NoticeService extends Service { const config = this.toObject(value, {}); return { max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, + default_express_code: 'STO', + default_platform_code: 'TB', ...config, }; }; diff --git a/app/service/systems/order_delivery_migration.js b/app/service/systems/order_delivery_migration.js new file mode 100644 index 0000000..15d1085 --- /dev/null +++ b/app/service/systems/order_delivery_migration.js @@ -0,0 +1,643 @@ +'use strict'; + +const MainService = require('../main'); + +const OUTBOUND_STATUS = 'fin'; +const OUTBOUND_STATUS_TIMEOUT = 'timeout'; +const OUTBOUND_STEP = 4; +const DISPATCH_LANE = 'm4'; +const MAX_BATCH_SIZE = 1000; +const CURRENT_TABLE_PATTERN = /^wms_order_delivery_(\d+)$/; +const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]); + +/** + * 订单出库后迁移到配送表的同步服务。 + */ +class OrderDeliveryMigrationService extends MainService { + /** + * 同步当前仓库分表中已出库订单到配送表。 + * + * @param {Object} data 请求参数。 + * @param {number|Array} [data.warehouseId] 单个仓库ID或仓库ID列表。 + * @param {Array} [data.warehouseIds] 仓库ID列表。 + * @return {Promise} 同步结果。 + */ + async syncOutboundOrdersToDelivery(data = {}) { + return this.syncOutboundOrdersByStatus(data, { + outboundStatuses: [ OUTBOUND_STATUS ], + persistTimeoutState: true, + }); + } + + /** + * 重试出库超时订单并继续迁移到配送表。 + * + * @param {Object} data 请求参数。 + * @param {number|Array} [data.warehouseId] 单个仓库ID或仓库ID列表。 + * @param {Array} [data.warehouseIds] 仓库ID列表。 + * @return {Promise} 同步结果。 + */ + async retryTimeoutOutboundOrdersToDelivery(data = {}) { + return this.syncOutboundOrdersByStatus(data, { + outboundStatuses: [ OUTBOUND_STATUS_TIMEOUT ], + persistTimeoutState: false, + }); + } + + /** + * 按指定出库状态同步订单到配送表。 + * + * @param {Object} data 请求参数。 + * @param {number|Array} [data.warehouseId] 单个仓库ID或仓库ID列表。 + * @param {Array} [data.warehouseIds] 仓库ID列表。 + * @param {Object} [options] 迁移控制参数。 + * @param {Array} [options.outboundStatuses] 需要迁移的出库状态。 + * @param {number} [options.queryTimeoutMs] 单条数据库查询的超时时间。 + * @param {number} [options.executionTimeoutMs] 单仓库批次的执行超时时间。 + * @param {boolean} [options.persistTimeoutState] 失败后是否将源订单标记为出库超时。 + * @return {Promise} 同步结果。 + */ + async syncOutboundOrdersByStatus(data = {}, options = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const explicitWarehouseIds = this.normalizeWarehouseIds(requestData); + const warehouseIds = explicitWarehouseIds.length > 0 + ? explicitWarehouseIds + : await this.listCurrentWarehouseIds(); + + const results = []; + let remaining = MAX_BATCH_SIZE; + let totalSelected = 0; + let totalCreated = 0; + let totalSkipped = 0; + let totalTimeout = 0; + + for (const warehouseId of warehouseIds) { + if (remaining <= 0) { + break; + } + + const batchLimit = Math.min(remaining, MAX_BATCH_SIZE); + const batchResult = await this.syncOutboundOrdersForWarehouse(warehouseId, batchLimit, options); + + results.push(batchResult); + totalSelected += batchResult.selectedCount; + totalCreated += batchResult.createdCount; + totalSkipped += batchResult.skippedCount; + totalTimeout += Number(batchResult.timeoutCount || 0); + remaining -= batchResult.selectedCount; + } + + return { + warehouseIds, + batchSize: MAX_BATCH_SIZE, + outboundStatuses: this.normalizeOutboundStatuses(options.outboundStatuses), + totalSelected, + totalCreated, + totalSkipped, + totalTimeout, + results, + }; + } + + /** + * 规范化仓库ID列表。 + * + * @param {Object} data 请求参数。 + * @return {Array} 仓库ID列表。 + */ + normalizeWarehouseIds(data = {}) { + if (!this.isPlainObject(data)) { + return []; + } + + const candidateValues = Array.isArray(data.warehouseIds) + ? data.warehouseIds + : [ data.warehouseId ?? data.warehouse_id ].filter(value => value !== undefined && value !== null && value !== ''); + + return Array.from(new Set(candidateValues + .map(value => Number(value)) + .filter(value => Number.isFinite(value) && value > 0))) + .sort((left, right) => left - right); + } + + /** + * 获取当前库中存在的订单工作台仓库ID。 + * + * @return {Promise>} 仓库ID列表。 + */ + async listCurrentWarehouseIds() { + const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + + if (!factory || typeof factory.listManagedTableNames !== 'function') { + return []; + } + + const tableNames = await factory.listManagedTableNames(); + + return Array.from(new Set((Array.isArray(tableNames) ? tableNames : []) + .map(tableName => { + const matched = CURRENT_TABLE_PATTERN.exec(String(tableName || '')); + return matched ? Number(matched[1]) : null; + }) + .filter(value => Number.isFinite(value) && value > 0))) + .sort((left, right) => left - right); + } + + /** + * 规范化需要迁移的出库状态。 + * + * @param {Array|string} outboundStatuses 目标状态。 + * @return {Array} 规范化后的状态列表。 + */ + normalizeOutboundStatuses(outboundStatuses = [ OUTBOUND_STATUS ]) { + const candidates = Array.isArray(outboundStatuses) + ? outboundStatuses + : [ outboundStatuses ]; + + const normalizedStatuses = Array.from(new Set(candidates + .map(value => String(value || '').trim()) + .filter(Boolean))); + + return normalizedStatuses.length > 0 ? normalizedStatuses : [ OUTBOUND_STATUS ]; + } + + /** + * 构造 Sequelize 查询参数。 + * + * @param {Object|null} transaction 事务对象。 + * @param {number} [queryTimeoutMs] 查询超时时间。 + * @return {Object} Sequelize 查询参数。 + */ + buildMigrationQueryOptions(transaction, queryTimeoutMs) { + const queryOptions = {}; + + if (transaction) { + queryOptions.transaction = transaction; + } + + const normalizedTimeoutMs = Number(queryTimeoutMs); + if (Number.isFinite(normalizedTimeoutMs) && normalizedTimeoutMs > 0) { + queryOptions.timeout = normalizedTimeoutMs; + } + + return queryOptions; + } + + /** + * 识别可重试的出库迁移错误。 + * + * @param {Error} error 运行时错误。 + * @return {{ retryable: boolean, category: string, message: string }} 错误分类结果。 + */ + getOutboundMigrationErrorInfo(error) { + const errorMessage = String(error && error.message || ''); + const errorName = String(error && error.name || ''); + const parentError = error && error.parent ? error.parent : null; + const errorCode = parentError && (parentError.code || parentError.errno) + ? parentError.code || parentError.errno + : error && (error.code || error.errno); + const normalizedMessage = errorMessage.toLowerCase(); + + if (errorName === 'SequelizeTimeoutError' || errorName === 'TimeoutError' || errorCode === 'ETIMEDOUT') { + return { + retryable: true, + category: 'timeout', + message: errorMessage, + }; + } + + if (errorName === 'SequelizeDatabaseError') { + if (normalizedMessage.includes('lock wait timeout')) { + return { + retryable: true, + category: 'lock_wait_timeout', + message: errorMessage, + }; + } + + if (RETRYABLE_DATABASE_ERROR_CODES.has(errorCode) || normalizedMessage.includes('deadlock')) { + return { + retryable: true, + category: 'deadlock', + message: errorMessage, + }; + } + } + + return { + retryable: false, + category: 'other', + message: errorMessage, + }; + } + + /** + * 将指定仓库内的源订单标记为出库超时。 + * + * @param {number} warehouseId 仓库ID。 + * @param {Array} orderIds 源订单ID列表。 + * @param {number} [queryTimeoutMs] 更新语句超时时间。 + * @return {Promise} 受影响行数。 + */ + async markOutboundOrdersTimeout(warehouseId, orderIds, queryTimeoutMs) { + const normalizedWarehouseId = Number(warehouseId); + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(value => Number(value)) + .filter(value => Number.isFinite(value) && value > 0))); + + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不能为空'); + } + + if (normalizedOrderIds.length === 0) { + return 0; + } + + const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + + if (!orderFactory || typeof orderFactory.getCurrentModel !== 'function') { + throw new Error('订单工厂未初始化'); + } + + const sourceOrderModel = await orderFactory.getCurrentModel(normalizedWarehouseId); + const { Op } = this.ctx.app.Sequelize; + const updateValues = { + outbound_status: OUTBOUND_STATUS_TIMEOUT, + step: OUTBOUND_STEP, + updated_at: new Date(), + }; + const updateResult = await sourceOrderModel.update(updateValues, { + where: { + warehouse_id: normalizedWarehouseId, + id: { + [Op.in]: normalizedOrderIds, + }, + }, + ...this.buildMigrationQueryOptions(null, queryTimeoutMs), + }); + + return Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + } + + /** + * 构造配送表去重键。 + * + * @param {Object} row 订单行数据。 + * @return {string} 去重键。 + */ + buildDispatchKey(row) { + if (!this.isPlainObject(row)) { + return ''; + } + + const deliveryOrderCode = String(row.delivery_order_code || '').trim(); + const storeId = String(row.store_id || '').trim(); + const warehouseId = String(row.warehouse_id || '').trim(); + + if (!deliveryOrderCode || !storeId || !warehouseId) { + return ''; + } + + return `${deliveryOrderCode}::${storeId}::${warehouseId}`; + } + + /** + * 构造配送表插入行。 + * + * @param {Object} row 当前订单工作台数据。 + * @return {Object} 可写入配送表的数据。 + */ + buildDispatchRow(row) { + const payload = { + ...(row || {}), + }; + + delete payload.dispatch_lane; + + return { + ...payload, + dispatch_lane: DISPATCH_LANE, + }; + } + + /** + * 构造商品明细迁移行。 + * + * @param {Object} row 当前订单商品明细行。 + * @param {number} targetOrderId 配送表订单ID。 + * @return {Object} 可写入配送明细表的数据。 + */ + buildDispatchItemRow(row, targetOrderId) { + return { + ...(row || {}), + order_id: targetOrderId, + }; + } + + /** + * 获取订单与商品明细迁移所需的模型。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 迁移模型集合。 + */ + async getMigrationModels(warehouseId) { + const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; + const itemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory; + + if (!orderFactory || typeof orderFactory.getCurrentModel !== 'function' || typeof orderFactory.getDispatchModel !== 'function') { + throw new Error('订单工厂未初始化'); + } + + if (!itemsFactory || typeof itemsFactory.getCurrentModel !== 'function' || typeof itemsFactory.getDispatchModel !== 'function') { + throw new Error('订单商品工厂未初始化'); + } + + return { + sourceOrderModel: await orderFactory.getCurrentModel(warehouseId), + targetOrderModel: await orderFactory.getDispatchModel(warehouseId), + sourceItemModel: await itemsFactory.getCurrentModel(warehouseId), + targetItemModel: await itemsFactory.getDispatchModel(warehouseId), + }; + } + + /** + * 将配送表订单行转换为订单ID映射。 + * + * @param {Array} rows 配送表订单行。 + * @return {Map} 业务键到订单ID的映射。 + */ + buildTargetOrderIdMap(rows) { + return new Map((Array.isArray(rows) ? rows : []) + .map(row => { + const key = this.buildDispatchKey(row); + const orderId = Number(row && row.id); + + if (!key || !Number.isFinite(orderId) || orderId <= 0) { + return null; + } + + return [ key, orderId ]; + }) + .filter(Boolean)); + } + + /** + * 同步指定仓库的已出库订单。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {number} [limit=1000] 单次处理数量上限。 + * @param {Object} [options] 迁移控制参数。 + * @param {Array} [options.outboundStatuses] 需要迁移的出库状态。 + * @param {number} [options.queryTimeoutMs] 单条数据库查询的超时时间。 + * @param {number} [options.executionTimeoutMs] 单仓库批次的执行超时时间。 + * @param {boolean} [options.persistTimeoutState] 失败后是否将源订单标记为出库超时。 + * @return {Promise} 同步结果。 + */ + async syncOutboundOrdersForWarehouse(warehouseId, limit = MAX_BATCH_SIZE, options = {}) { + const normalizedWarehouseId = Number(warehouseId); + + if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('仓库ID不能为空'); + } + + const batchLimit = Math.min( + Math.max(Number(limit) || MAX_BATCH_SIZE, 1), + MAX_BATCH_SIZE + ); + const outboundStatuses = this.normalizeOutboundStatuses(options.outboundStatuses); + const queryTimeoutMs = Number(options.queryTimeoutMs); + const executionTimeoutMs = Number(options.executionTimeoutMs); + const persistTimeoutState = Boolean(options.persistTimeoutState); + const deadlineAt = Number.isFinite(executionTimeoutMs) && executionTimeoutMs > 0 + ? Date.now() + executionTimeoutMs + : 0; + const transaction = await this.ctx.model.transaction(); + const { Op } = this.ctx.app.Sequelize; + let sourceRows = []; + let selectedSourceOrderIds = []; + + const assertMigrationDeadline = stage => { + if (deadlineAt > 0 && Date.now() > deadlineAt) { + const timeoutError = new Error(`仓库 ${normalizedWarehouseId} ${stage} 执行超时`); + timeoutError.code = 'OUTBOUND_MIGRATION_TIMEOUT'; + throw timeoutError; + } + }; + + try { + assertMigrationDeadline('出库迁移'); + const { + sourceOrderModel, + targetOrderModel, + sourceItemModel, + targetItemModel, + } = await this.getMigrationModels(normalizedWarehouseId); + + assertMigrationDeadline('查询源订单'); + sourceRows = await sourceOrderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + outbound_status: { + [Op.in]: outboundStatuses, + }, + step: OUTBOUND_STEP, + }, + order: [[ 'id', 'ASC' ]], + limit: batchLimit, + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + + selectedSourceOrderIds = Array.from(new Set((Array.isArray(sourceRows) ? sourceRows : []) + .map(row => Number(row && row.id)) + .filter(value => Number.isFinite(value) && value > 0))); + + if (!Array.isArray(sourceRows) || sourceRows.length === 0) { + await transaction.commit(); + + return { + warehouseId: normalizedWarehouseId, + selectedCount: 0, + createdCount: 0, + skippedCount: 0, + timeoutCount: 0, + }; + } + + const invalidSourceRows = sourceRows.filter(row => !this.buildDispatchKey(row)); + + if (invalidSourceRows.length > 0) { + const invalidRowIds = invalidSourceRows + .map(row => Number(row && row.id)) + .filter(value => Number.isFinite(value) && value > 0); + + throw new Error(`选中的源订单存在缺少 delivery_order_code/store_id/warehouse_id 的记录${invalidRowIds.length > 0 ? `: ${invalidRowIds.join(', ')}` : ''}`); + } + + const validSourceRows = sourceRows; + const sourceOrderRowMap = new Map(validSourceRows + .map(row => [ Number(row.id), row ]) + .filter(([ rowId, row ]) => Number.isFinite(rowId) && rowId > 0 && this.buildDispatchKey(row))); + const deliveryOrderCodes = Array.from(new Set(validSourceRows + .map(row => String(row.delivery_order_code || '').trim()) + .filter(Boolean))); + const sourceOrderIds = Array.from(sourceOrderRowMap.keys()); + + let existingRows = []; + if (deliveryOrderCodes.length > 0) { + assertMigrationDeadline('查询配送表订单'); + existingRows = await targetOrderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + delivery_order_code: { + [Op.in]: deliveryOrderCodes, + }, + }, + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + } + + const existingKeySet = new Set((Array.isArray(existingRows) ? existingRows : []) + .map(row => this.buildDispatchKey(row)) + .filter(Boolean)); + + const rowsToCreate = validSourceRows + .filter(row => !existingKeySet.has(this.buildDispatchKey(row))) + .map(row => this.buildDispatchRow(row)); + + if (rowsToCreate.length > 0) { + assertMigrationDeadline('创建配送表订单'); + await targetOrderModel.bulkCreate(rowsToCreate, { + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + ignoreDuplicates: true, + }); + } + + assertMigrationDeadline('查询配送表订单'); + const targetRows = deliveryOrderCodes.length > 0 + ? await targetOrderModel.findAll({ + where: { + warehouse_id: normalizedWarehouseId, + delivery_order_code: { + [Op.in]: deliveryOrderCodes, + }, + }, + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }) + : []; + const targetOrderIdMap = this.buildTargetOrderIdMap(targetRows); + + if (sourceOrderIds.length > 0) { + assertMigrationDeadline('查询商品明细'); + const sourceItems = await sourceItemModel.findAll({ + where: { + order_id: { + [Op.in]: sourceOrderIds, + }, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + + const validSourceItems = Array.isArray(sourceItems) + ? sourceItems.filter(item => Number.isFinite(Number(item && item.id))) + : []; + + const rowsToCreateItems = validSourceItems.map(item => { + const sourceOrder = sourceOrderRowMap.get(Number(item.order_id)); + const targetOrderId = targetOrderIdMap.get(this.buildDispatchKey(sourceOrder)); + + if (!Number.isFinite(targetOrderId) || targetOrderId <= 0) { + throw new Error(`无法找到订单 ${item.order_id} 对应的配送表订单ID`); + } + + return this.buildDispatchItemRow(item, targetOrderId); + }); + + if (rowsToCreateItems.length > 0) { + assertMigrationDeadline('创建商品明细'); + await targetItemModel.bulkCreate(rowsToCreateItems, { + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + ignoreDuplicates: true, + }); + } + + assertMigrationDeadline('删除源商品明细'); + await sourceItemModel.destroy({ + where: { + id: { + [Op.in]: validSourceItems.map(item => Number(item.id)).filter(value => Number.isFinite(value) && value > 0), + }, + }, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + } + + if (sourceOrderIds.length > 0) { + assertMigrationDeadline('删除源订单'); + await sourceOrderModel.destroy({ + where: { + id: { + [Op.in]: sourceOrderIds, + }, + }, + ...this.buildMigrationQueryOptions(transaction, queryTimeoutMs), + }); + } + + await transaction.commit(); + + return { + warehouseId: normalizedWarehouseId, + selectedCount: sourceRows.length, + createdCount: rowsToCreate.length, + skippedCount: sourceRows.length - rowsToCreate.length, + timeoutCount: 0, + }; + } catch (error) { + await transaction.rollback(); + + const migrationErrorInfo = this.getOutboundMigrationErrorInfo(error); + const shouldPersistTimeoutState = persistTimeoutState && migrationErrorInfo.retryable && selectedSourceOrderIds.length > 0; + + if (shouldPersistTimeoutState) { + const timeoutCount = await this.markOutboundOrdersTimeout( + normalizedWarehouseId, + selectedSourceOrderIds, + queryTimeoutMs + ); + + return { + warehouseId: normalizedWarehouseId, + selectedCount: sourceRows.length, + createdCount: 0, + skippedCount: 0, + timeoutCount, + retryableFailure: true, + retryableFailureType: migrationErrorInfo.category, + retryableFailureMessage: migrationErrorInfo.message, + }; + } + + if (migrationErrorInfo.retryable) { + return { + warehouseId: normalizedWarehouseId, + selectedCount: sourceRows.length, + createdCount: 0, + skippedCount: 0, + timeoutCount: 0, + retryableFailure: true, + retryableFailureType: migrationErrorInfo.category, + retryableFailureMessage: migrationErrorInfo.message, + }; + } + + throw error; + } + } +} + +module.exports = OrderDeliveryMigrationService; diff --git a/app/service/systems/order_outbound.js b/app/service/systems/order_outbound.js new file mode 100644 index 0000000..565a422 --- /dev/null +++ b/app/service/systems/order_outbound.js @@ -0,0 +1,89 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +const OUTBOUND_STATUS = 'fin'; +const OUTBOUND_STEP = 4; + +/** + * 订单出库状态服务。 + * 仅用于内部把订单标记为出库,不对外暴露通用 method。 + */ +class OrderOutboundService extends OrderBaseService { + /** + * 将订单标记为出库。 + * + * 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。 + * 仅更新出库状态相关字段:outbound_status、step、delivery_time、updated_at。 + * + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息,包含出库状态与更新数量。 + */ + async markOutboundOrder(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = this.getWarehouseId(); + const orderIds = this.normalizeOrderIds(requestData); + + if (orderIds.length === 0) { + throw new Error('订单ID不能为空'); + } + + const model = await this.getOrderModel('order', warehouseId); + const now = new Date(); + const where = this.buildOrderWhere(orderIds, warehouseId); + const updateValues = { + outbound_status: OUTBOUND_STATUS, + step: OUTBOUND_STEP, + delivery_time: now, + updated_at: now, + }; + + const updateResult = await model.update(updateValues, { + where, + }); + + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + if (affectedRows <= 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const updatedOrders = await model.findAll({ + where, + raw: true, + }); + + if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ])); + const normalizedOrders = orderIds + .map(orderId => orderMap.get(orderId)) + .filter(Boolean) + .map(order => ({ + id: order.id, + outbound_status: order.outbound_status, + step: Number(order.step ?? OUTBOUND_STEP), + delivery_time: order.delivery_time, + updated_at: order.updated_at, + })); + + if (normalizedOrders.length === 0) { + throw new Error('订单不存在或不属于当前仓库'); + } + + const firstOrder = normalizedOrders[0]; + + return { + id: firstOrder.id, + outbound_status: firstOrder.outbound_status, + step: firstOrder.step, + delivery_time: firstOrder.delivery_time, + updated_at: firstOrder.updated_at, + updated_count: affectedRows, + ids: normalizedOrders.map(order => order.id), + }; + } +} + +module.exports = OrderOutboundService; diff --git a/app/service/systems/order_pending_exception.js b/app/service/systems/order_pending_exception.js new file mode 100644 index 0000000..51c5476 --- /dev/null +++ b/app/service/systems/order_pending_exception.js @@ -0,0 +1,43 @@ +'use strict'; + +const OrderBaseService = require('../systemMethods/order/base'); + +class OrderPendingExceptionService extends OrderBaseService { + /** + * 将订单标记为待处理异常。 + * + * 兼容单条与批量入参,支持 id、order_id、ids 三种订单 ID 写法。 + * 异常文本会保留在订单标记字段上,供待处理异常列表展示或追踪;审核/反审只负责状态流转,不会主动清空该字段。 + * + * @param {Object} data 请求体。 + * @return {Promise} 更新后的订单信息,包含异常文本与更新数量。 + */ + async markPendingException(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const exceptionText = String( + requestData.exception_text + ?? requestData.exception_reason + ?? requestData.remark + ?? requestData.reason + ?? '' + ).trim(); + + if (!exceptionText) { + throw new Error('异常文本不能为空'); + } + + const result = await this.updateOrderInspectionState(requestData, 'error', { + extraUpdateValues: { + order_flag: exceptionText, + }, + }); + + return { + ...result, + exception_text: exceptionText, + order_flag: exceptionText, + }; + } +} + +module.exports = OrderPendingExceptionService; diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js new file mode 100644 index 0000000..b6cbf50 --- /dev/null +++ b/app/service/systems/order_storage_allocation.js @@ -0,0 +1,636 @@ +'use strict'; + +const MainService = require('../main'); + +const STORAGE_STATUS_FIN = 'fin'; +const STORAGE_STATUS_ERROR = 'error'; +const ORDER_STEP_EXCEPTION = 3; + +/** + * 将输入值规范化为布尔值。 + * + * @param {unknown} value 待转换的值。 + * @param {boolean} [defaultValue=false] 空值时的默认布尔值。 + * @return {boolean} 是否为真。 + */ +function normalizeBooleanFlag(value, defaultValue = false) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + if (typeof value === 'string') { + return [ '1', 'Y', 'YES', 'TRUE', 'ON' ].includes(value.trim().toUpperCase()); + } + + return false; +} + +/** + * 将输入值转换为有限数字。 + * + * @param {unknown} value 待转换的值。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 转换后的数字。 + */ +function toNumber(value, defaultValue = 0) { + const normalized = Number(value); + + return Number.isFinite(normalized) ? normalized : defaultValue; +} + +/** + * 将模型记录转换为普通对象。 + * + * @param {unknown} record 模型记录。 + * @return {Object|null} 普通对象。 + */ +function toPlainRecord(record) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; +} + +/** + * 解析日期值并返回时间戳。 + * + * @param {unknown} value 日期值。 + * @return {number} 时间戳或 Number.MAX_SAFE_INTEGER。 + */ +function toTimeValue(value) { + if (!value) { + return Number.MAX_SAFE_INTEGER; + } + + const timeValue = new Date(value).getTime(); + return Number.isFinite(timeValue) ? timeValue : Number.MAX_SAFE_INTEGER; +} + +/** + * 对可分配库存按优先级排序。 + * + * @param {Object} left 左侧库存。 + * @param {Object} right 右侧库存。 + * @param {boolean} prioritizeStorage 是否优先使用存储储位。 + * @return {number} 排序结果。 + */ +function compareStorageRows(left, right, prioritizeStorage) { + const leftPickPriority = prioritizeStorage ? (left.is_preferred_pick ? 1 : 0) : 0; + const rightPickPriority = prioritizeStorage ? (right.is_preferred_pick ? 1 : 0) : 0; + + if (leftPickPriority !== rightPickPriority) { + return leftPickPriority - rightPickPriority; + } + + const leftHasProductionDate = Boolean(left.production_date); + const rightHasProductionDate = Boolean(right.production_date); + + if (leftHasProductionDate !== rightHasProductionDate) { + return leftHasProductionDate ? -1 : 1; + } + + if (leftHasProductionDate && rightHasProductionDate) { + const productionDiff = toTimeValue(left.production_date) - toTimeValue(right.production_date); + if (productionDiff !== 0) { + return productionDiff; + } + } + + const inboundDiff = toTimeValue(left.inbound_time) - toTimeValue(right.inbound_time); + if (inboundDiff !== 0) { + return inboundDiff; + } + + return toNumber(left.id, 0) - toNumber(right.id, 0); +} + +/** + * 生成库存不足提示文本。 + * + * @param {Array} shortageItems 缺货条目。 + * @return {string} 提示文本。 + */ +function buildShortageMessage(shortageItems = []) { + const parts = shortageItems + .filter(item => item && Number(item.stock_id) > 0) + .map(item => `sku(${item.stock_id}),数量:${item.required_quantity},库位数量:${item.allocated_quantity}`); + + return parts.length > 0 ? `库存不足:${parts.join('|')}` : ''; +} + +/** + * 规范化订单 ID 列表。 + * + * @param {Object} data 请求体。 + * @return {number[]} 订单 ID 列表。 + */ +function normalizeOrderIds(data = {}) { + const requestData = data && typeof data === 'object' ? data : {}; + const rawValues = []; + + if (Array.isArray(requestData.order_ids)) { + rawValues.push(...requestData.order_ids); + } else if (Array.isArray(requestData.orderIds)) { + rawValues.push(...requestData.orderIds); + } else if (Array.isArray(requestData.ids)) { + rawValues.push(...requestData.ids); + } else if (typeof requestData.order_ids === 'string') { + rawValues.push(...requestData.order_ids.split(',')); + } else if (typeof requestData.orderIds === 'string') { + rawValues.push(...requestData.orderIds.split(',')); + } else if (typeof requestData.ids === 'string') { + rawValues.push(...requestData.ids.split(',')); + } else if (requestData.order_ids !== undefined && requestData.order_ids !== null && requestData.order_ids !== '') { + rawValues.push(requestData.order_ids); + } else if (requestData.orderIds !== undefined && requestData.orderIds !== null && requestData.orderIds !== '') { + rawValues.push(requestData.orderIds); + } else if (requestData.ids !== undefined && requestData.ids !== null && requestData.ids !== '') { + rawValues.push(requestData.ids); + } else if (requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '') { + rawValues.push(requestData.order_id); + } else if (requestData.orderId !== undefined && requestData.orderId !== null && requestData.orderId !== '') { + rawValues.push(requestData.orderId); + } else if (requestData.id !== undefined && requestData.id !== null && requestData.id !== '') { + rawValues.push(requestData.id); + } + + const orderIds = rawValues + .map(value => Number(String(value).trim())) + .filter(value => Number.isFinite(value) && value > 0); + + return Array.from(new Set(orderIds)); +} + +/** + * 订单储位分配公共服务。 + * 负责订单、库存、库位的分配编排,并写入 wms_picking。 + */ +class OrderStorageAllocationService extends MainService { + /** + * 按订单批量分配储位。 + * + * 入参支持以下字段: + * - `allow_storage_location` / `allowStorageLocation` / `is_allow_storage` / `isAllowStorage` + * - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id` + * - `warehouse_id` / `warehouseId`(可选,默认使用当前上下文仓库) + * + * 分配规则: + * - 先过滤掉已经完成储位分配的订单 + * - 允许时优先使用存储储位,再使用分拣储位 + * - FIFO 先按生产日期,再按入库时间 + * - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常 + * + * @param {Object} data 请求体。 + * @return {Promise} 分配结果。 + */ + async allocatePicking(data = {}) { + const { ctx, app } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = toNumber(requestData.warehouse_id ?? requestData.warehouseId ?? ctx.user?.store_id, 0); + const orderIds = normalizeOrderIds(requestData); + const allowStorageLocation = normalizeBooleanFlag( + requestData.allow_storage_location + ?? requestData.allowStorageLocation + ?? requestData.is_allow_storage + ?? requestData.isAllowStorage + ); + + if (warehouseId <= 0) { + return { + code: 400, + message: '缺少仓库上下文', + data: null, + }; + } + + if (orderIds.length === 0) { + return { + code: 400, + message: '订单ID不能为空', + data: null, + }; + } + + const transaction = await ctx.model.transaction(); + const { Op } = app.Sequelize; + const now = new Date(); + + try { + const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); + const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const pickingModel = ctx.model.Picking; + + if (!pickingModel || typeof pickingModel.bulkCreate !== 'function') { + throw new Error('wms_picking 模型不可用'); + } + + const orderRows = await orderModel.findAll({ + where: { + id: { + [Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const orderMap = new Map(); + for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { + const plainOrder = toPlainRecord(orderRow); + if (!plainOrder || !Number(plainOrder.id)) { + continue; + } + + orderMap.set(Number(plainOrder.id), plainOrder); + } + + const pendingOrderIds = []; + const skippedOrders = []; + + for (const orderId of orderIds) { + const orderRow = orderMap.get(orderId); + + if (!orderRow) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + skipped_reason: 'not_found', + }); + continue; + } + + if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) { + skippedOrders.push({ + order_id: orderId, + status: 'skipped', + storage_status: orderRow.storage_status, + skipped_reason: 'already_allocated', + }); + continue; + } + + pendingOrderIds.push(orderId); + } + + if (pendingOrderIds.length === 0) { + await transaction.commit(); + return { + code: 200, + message: '没有需要分配的订单', + data: { + warehouse_id: warehouseId, + allow_storage_location: allowStorageLocation, + requested_order_ids: orderIds, + pending_order_ids: [], + skipped_orders: skippedOrders, + orders: skippedOrders, + picking_count: 0, + }, + }; + } + + const orderItemRows = await orderItemModel.findAll({ + where: { + order_id: { + [Op.in]: pendingOrderIds, + }, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + + const orderItemsByOrderId = new Map(); + const stockIdSet = new Set(); + + for (const orderItemRow of Array.isArray(orderItemRows) ? orderItemRows : []) { + const plainItem = toPlainRecord(orderItemRow); + if (!plainItem || !Number(plainItem.order_id)) { + continue; + } + + const orderId = Number(plainItem.order_id); + const orderItems = orderItemsByOrderId.get(orderId) || []; + orderItems.push(plainItem); + orderItemsByOrderId.set(orderId, orderItems); + + const stockId = Number(plainItem.stock_id || 0); + if (stockId > 0) { + stockIdSet.add(stockId); + } + } + + const stockIds = Array.from(stockIdSet); + if (stockIds.length > 0) { + await ctx.model.StockWarehouse.findAll({ + where: { + id: { + [Op.in]: stockIds, + }, + warehouse_id: warehouseId, + is_valid: 'Y', + deleted_at: null, + }, + transaction, + lock: transaction.LOCK.UPDATE, + raw: true, + }); + } + + const storageRows = stockIds.length > 0 + ? await ctx.model.Storage.findAll({ + where: { + warehouse_id: warehouseId, + stock_id: { + [Op.in]: stockIds, + }, + is_enabled: 1, + delete_at: null, + available_quantity: { + [Op.gt]: 0, + }, + }, + include: [ + { + model: ctx.model.LocationSpace, + as: 'space', + required: true, + attributes: [ 'id', 'space_code', 'custom_name', 'is_preferred_pick', 'pick_sequence', 'pick_priority' ], + include: [ + { + model: ctx.model.LocationType, + as: 'locationType', + required: true, + attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ], + where: { + allow_allocation: 1, + is_active: 1, + }, + }, + ], + }, + ], + transaction, + lock: transaction.LOCK.UPDATE, + order: [[ 'id', 'ASC' ]], + }) + : []; + + const storageRowsByStockId = new Map(); + for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { + const plainStorage = toPlainRecord(storageRow); + if (!plainStorage || !Number(plainStorage.id) || !Number(plainStorage.stock_id)) { + continue; + } + + const space = toPlainRecord(plainStorage.space) || {}; + const locationType = toPlainRecord(space.locationType) || {}; + const normalizedStorage = { + ...plainStorage, + quantity: toNumber(plainStorage.quantity, 0), + locked_quantity: toNumber(plainStorage.locked_quantity, 0), + available_quantity: toNumber(plainStorage.available_quantity, 0), + production_date: plainStorage.production_date || null, + inbound_time: plainStorage.inbound_time || null, + space, + locationType, + space_name: String(space.custom_name || space.space_code || '').trim(), + is_preferred_pick: normalizeBooleanFlag(space.is_preferred_pick), + }; + + const stockId = Number(normalizedStorage.stock_id); + const currentStorageRows = storageRowsByStockId.get(stockId) || []; + currentStorageRows.push(normalizedStorage); + storageRowsByStockId.set(stockId, currentStorageRows); + } + + const policyCache = new Map(); + const pickingRows = []; + const stockAllocationMap = new Map(); + const storageAllocationMap = new Map(); + const orderResults = []; + + for (const orderId of pendingOrderIds) { + const orderRow = orderMap.get(orderId); + if (!orderRow) { + continue; + } + + const orderItems = (orderItemsByOrderId.get(orderId) || []) + .slice() + .sort((left, right) => { + const leftLineNo = toNumber(left.order_line_no, 0); + const rightLineNo = toNumber(right.order_line_no, 0); + + if (leftLineNo !== rightLineNo) { + return leftLineNo - rightLineNo; + } + + return toNumber(left.id, 0) - toNumber(right.id, 0); + }); + + const shortageItems = []; + let allocatedQuantityForOrder = 0; + + for (const orderItem of orderItems) { + const stockId = toNumber(orderItem.stock_id, 0); + const requiredQuantity = toNumber(orderItem.plan_qty ?? orderItem.planQty ?? orderItem.count ?? 0, 0); + + if (stockId <= 0 || requiredQuantity <= 0) { + shortageItems.push({ + stock_id: stockId, + required_quantity: requiredQuantity > 0 ? requiredQuantity : 0, + allocated_quantity: 0, + }); + continue; + } + + const policyEntry = policyCache.has(stockId) + ? policyCache.get(stockId) + : await ctx.service.systems.stockStore.getStoreWarehousePolicyConfigByStockId(stockId, transaction); + policyCache.set(stockId, policyEntry); + + const storageSeparationEnabled = normalizeBooleanFlag(policyEntry?.policyConfig?.storage_separation, true); + const allowStorageSpace = allowStorageLocation || !storageSeparationEnabled; + + const candidateStorageRows = (storageRowsByStockId.get(stockId) || []) + .filter(storageRow => allowStorageSpace || storageRow.is_preferred_pick) + .slice() + .sort((left, right) => compareStorageRows(left, right, allowStorageSpace)); + + let remainingQuantity = requiredQuantity; + let allocatedQuantityForItem = 0; + + for (const storageRow of candidateStorageRows) { + if (remainingQuantity <= 0) { + break; + } + + const currentAvailable = toNumber(storageRow.available_quantity, 0); + if (currentAvailable <= 0) { + continue; + } + + const allocationQuantity = Math.min(remainingQuantity, currentAvailable); + if (allocationQuantity <= 0) { + continue; + } + + await ctx.service.systems.storage.lockQuantity(storageRow.id, allocationQuantity, { transaction }); + + storageRow.available_quantity = currentAvailable - allocationQuantity; + storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) + allocationQuantity; + remainingQuantity -= allocationQuantity; + allocatedQuantityForItem += allocationQuantity; + allocatedQuantityForOrder += allocationQuantity; + + storageAllocationMap.set(storageRow.id, (storageAllocationMap.get(storageRow.id) || 0) + allocationQuantity); + stockAllocationMap.set(stockId, (stockAllocationMap.get(stockId) || 0) + allocationQuantity); + + pickingRows.push({ + order_id: orderId, + order_item_id: toNumber(orderItem.id, 0), + storage_id: storageRow.id, + quantity: allocationQuantity, + space_id: toNumber(storageRow.space_id, 0) || null, + space_name: String(storageRow.space_name || '').trim(), + status: 'pending', + created_at: now, + updated_at: now, + }); + } + + if (remainingQuantity > 0) { + shortageItems.push({ + stock_id: stockId, + required_quantity: requiredQuantity, + allocated_quantity: allocatedQuantityForItem, + }); + } + } + + const shortageMessage = buildShortageMessage(shortageItems); + const orderUpdateValues = shortageMessage + ? { + storage_status: STORAGE_STATUS_ERROR, + step: ORDER_STEP_EXCEPTION, + order_flag: shortageMessage, + updated_at: now, + } + : { + storage_status: STORAGE_STATUS_FIN, + order_flag: '', + updated_at: now, + }; + + await orderModel.update(orderUpdateValues, { + where: { + id: orderId, + warehouse_id: warehouseId, + }, + transaction, + }); + + orderResults.push({ + order_id: orderId, + storage_status: orderUpdateValues.storage_status, + allocated_quantity: allocatedQuantityForOrder, + shortage_message: shortageMessage || '', + status: shortageMessage ? 'error' : 'success', + }); + } + + for (const [ stockId, quantity ] of stockAllocationMap.entries()) { + if (quantity <= 0) { + continue; + } + + const stockRecord = await ctx.model.StockWarehouse.findByPk(stockId, { + transaction, + }); + + if (!stockRecord) { + throw new Error(`库存主记录不存在: ${stockId}`); + } + + await stockRecord.increment('locked_quantity', { + by: quantity, + transaction, + silent: true, + }); + await stockRecord.reload({ transaction }); + } + + if (pickingRows.length > 0) { + await pickingModel.bulkCreate(pickingRows, { + transaction, + }); + } + + await transaction.commit(); + + const errorOrderResults = orderResults.filter(item => item.status === 'error'); + const successOrderResults = orderResults.filter(item => item.status === 'success'); + const shortageMessages = errorOrderResults + .map(item => item.shortage_message) + .filter(Boolean); + + return { + code: 200, + message: shortageMessages.length > 0 + ? '储位分配完成,部分订单库存不足' + : '储位分配完成', + data: { + warehouse_id: warehouseId, + allow_storage_location: allowStorageLocation, + requested_order_ids: orderIds, + pending_order_ids: pendingOrderIds, + allocated_order_ids: successOrderResults.map(item => item.order_id), + shortage_order_ids: errorOrderResults.map(item => item.order_id), + skipped_orders: skippedOrders, + orders: [ ...skippedOrders, ...orderResults ], + picking_count: pickingRows.length, + stock_lock_summary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ + stock_id: stockId, + locked_quantity: quantity, + })), + storage_lock_summary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ + storage_id: storageId, + locked_quantity: quantity, + })), + shortage_messages: shortageMessages, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 兼容旧调用名称的储位分配入口。 + * + * @param {Object} data 请求体。 + * @return {Promise} 分配结果。 + */ + async allocateStorage(data = {}) { + return await this.allocatePicking(data); + } +} + +module.exports = OrderStorageAllocationService; \ No newline at end of file diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index fe5337d..d44cf2e 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -1,7 +1,73 @@ // app/service/system/platform.js const Service = require('egg').Service; +const DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS = 600; + class PlatformService extends Service { + getPlatformListCacheKey() { + return 'platform:list'; + } + + normalizePlatformRow(row) { + if (!row || typeof row !== 'object') { + return null; + } + + const code = String(row.code || '').trim(); + if (!code) { + return null; + } + + const name = String(row.name || '').trim(); + const defaultExpressInterface = String(row.default_express_interface || '').trim(); + + return { + code, + name, + default_express_interface: defaultExpressInterface, + value: code, + label: name || code, + }; + } + + async loadPlatformListFromDatabase() { + const rows = await this.ctx.model.Platform.findAll({ + attributes: [ 'code', 'name', 'default_express_interface' ], + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(row => this.normalizePlatformRow(row)) + .filter(Boolean); + } + + async getPlatformList() { + const cacheKey = this.getPlatformListCacheKey(); + + try { + const cachedList = await this.app.getCacheAsync(cacheKey); + if (cachedList !== null && cachedList !== undefined) { + return Array.isArray(cachedList) ? cachedList : []; + } + + const platformList = await this.loadPlatformListFromDatabase(); + await this.app.setCacheAsync(cacheKey, platformList, DEFAULT_PLATFORM_LIST_CACHE_TTL_SECONDS); + + return platformList; + } catch (error) { + this.ctx.logger.error('[PlatformService.getPlatformList] 获取平台列表失败', { + error: error.message, + stack: error.stack, + }); + throw error; + } + } + /** * 检查平台是否存在 * 逻辑: diff --git a/app/service/systems/polo_api.js b/app/service/systems/polo_api.js index af7289f..bedfc41 100644 --- a/app/service/systems/polo_api.js +++ b/app/service/systems/polo_api.js @@ -1,198 +1,173 @@ 'use strict'; const Service = require('egg').Service; -const poloApiConfig = require('../../../config/poloapi'); - -const crypto = require('crypto'); +const PoloApiClient = require('../../lib/polo_api_client'); class PoloApiService extends Service { + /** + * @param {object} ctx - Egg 上下文对象。 + */ constructor(ctx) { super(ctx); - this.configPoloApi = poloApiConfig; + this.client = new PoloApiClient(ctx); } - // 批量组装订单JSON - getJsonDatas(expressConfig, list) { - const cal = new Date(); - const year = cal.getFullYear(); - const month = cal.getMonth() + 1; - const day = cal.getDate() + 3; - const day1 = cal.getDate() + 4; - const sb1 = this._formatPickupDate(year, month, day); - const sb2 = this._formatPickupDate(year, month, day1); + /** + * 测试 Polo API 请求并返回请求结果。 + * + * @returns {Promise} request() 的返回结果。 + */ + async test() { + return this.client.request({ + method: 'Differ.JH.LogisticsPlatFeatures', + platid: 556, + bizcontent: {}, + }); + } + async test2() { + return this.client.request({ + method: 'Differ.JH.LogisticsPlatFeatures', + platid: 556, + bizcontent: {}, + }); + } + /** + * 快手取号。 + * + * @param {object} [options={}] - 快手取号入参。 + * @param {string} [options.express_id=''] - 快手平台对应的承运商编码。 + * @param {object} [options.wmsOrder={}] - WMS 订单信息。 + * @param {object} [options.expressConfig={}] - 发件方与店铺配置。 + * @returns {Promise} 接口响应 data。 + */ + async kuaishou(options = {}) { + const { + express_id = '', + wmsOrder = {}, + expressConfig = {}, + } = options; + const { + sourceId = '', + sourceOrderCode = '', + postcode = '', + wareHouseId = 0, + storeId = 0, + items = '', + goodsCount = 0, + orderWeight = 0, + address = '', + name = '', + expAreaName = '', + cityName = '', + province = '', + tempMobile = '', + tel = '', + } = wmsOrder; + const { + storeName = '', + address: senderAddress = '', + senderName = '', + districtName = '', + cityName: senderCityName = '', + senderTel = '', + provinceName = '', + siteCode = '', + clientId = '', + } = expressConfig; - const orders = []; - for (const wmsOrder of list) { - let txLogisticID = wmsOrder.sourceId; - txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID; - if (wmsOrder.postcode === 'p10') { - if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19); - } else { - if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28); + const platid = 556; + const method = 'Differ.JH.Logistics.PostOrder'; + const shoptype = 'JH_001'; + const sourceIdText = String(sourceId || ''); + const sourceOrderCodeText = String(sourceOrderCode || ''); + const [senderArea = '', senderTown = ''] = String(districtName || '').split(';'); + const mobile = tempMobile || tel || ''; + const cpcode = express_id || ''; + const txLogisticID = sourceIdText.replace(/_/g, ''); + let cnname = ''; + + if (!(wareHouseId === 5400 || storeId === 58303)) { + const firstItem = String(items || '').split('|')[0] || ''; + const itemFields = firstItem.split(','); + if (itemFields.length > 2) { + cnname = itemFields[2]; } - txLogisticID = txLogisticID.replace(/_/g, ''); - - // 快递公司代码 - const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || ''; - - // 商品名 - let cnname = ''; - const ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303); - if (ycflag) { - const items = wmsOrder.items || ''; - const splitStr = items.split('|'); - if (splitStr.length > 0) { - const s = splitStr[0]; - const sArr = s.split(','); - if (sArr.length > 2) cnname = sArr[2]; - } - } else { - cnname = 'sp'; - } - - // 收件人手机号 - const mobile = wmsOrder.tempMobile || wmsOrder.tel || ''; - - /* - order对象结构(41-77): - { - businessplat, ismultiplepieces, businesstype, cpcode, customercode, customername, - goods: [goods对象结构(49-56)], - logisticsproductname, logistictype, mainsubpaymode, needencrypt, numpackage, - orderno, ordersource, ordertype, plattradeno, ProviderID, providercode, - receiver: receiver对象结构(59-65), sender: sender对象结构(66-75), shipperno, sitecode, Inputsite, transtype - } - goods对象结构(49-56): - { - cnname, count, unit, currencytype, Unit, weight, price - } - receiver对象结构(59-65): - { - address, name, area, city, mobile, province - } - sender对象结构(66-75): - { - country, Company, address, name, area, town, city, phone, mobile, tel, province - } - */ - // 组装订单对象(下标范围:约第41-77行) - const order = { // [order对象开始 41] - businessplat: 'OTHERS', // 41 - ismultiplepieces: '0', - businesstype: 'JH_Normal', - cpcode, - customercode: '', - customername: expressConfig.storeProperty || '测试', - goods: [{ // [goods对象开始 49] - cnname, - count: String(wmsOrder.goodsCount), - unit: '属性', - currencytype: 'CNY', - Unit: '', - weight: String(wmsOrder.orderWeight), - price: '0.0', - }], // [goods对象结束 56] - logisticsproductname: 'JH_02', - logistictype: cpcode, - mainsubpaymode: '1', - needencrypt: '1', - numpackage: '1', - orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id), - ordersource: 'KUAI_SHOU', - ordertype: 'JH_Normal', - plattradeno: wmsOrder.sourceOrderCode || txLogisticID, - ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''), - providercode: cpcode, - receiver: { // [receiver对象开始 59] - address: wmsOrder.address, - name: wmsOrder.name, - area: wmsOrder.expAreaName, - city: wmsOrder.cityName, - mobile, - province: wmsOrder.province, - }, // [receiver对象结束 65] - sender: { // [sender对象开始 66] - country: 'CN', - Company: expressConfig.storeName, - address: expressConfig.address, - name: expressConfig.senderName, - area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0], - town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined, - city: expressConfig.cityName, - phone: expressConfig.senderTel, - mobile: expressConfig.senderTel, - tel: expressConfig.senderTel, - province: expressConfig.provinceName, - }, // [sender对象结束 75] - shipperno: [ 'p22', 'p35', 'p10' ].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId, - sitecode: expressConfig.siteCode || '', - Inputsite: expressConfig.siteCode || '', - transtype: '0', - // 省略部分特殊字段和extraInfo,后续可补充 - }; // [order对象结束 77] - // 特殊字段 - if (wmsOrder.postcode === 'p10') { - order.pickUpDate = sb1; - order.pickUpEndDate = sb2; - } - orders.push(order); + } else { + cnname = 'sp'; } - const body = JSON.stringify({ orders, shoptype: 'JH_001' }); - - // 组装url参数 - const urlParams = { - method: 'Differ.JH.Logistics.PostOrder', - appkey: this.configPoloApi.appKey, - token: expressConfig.sessionKey, - platid: this.configPoloApi.platid, - version: this.configPoloApi.version, - bizcontent: encodeURIComponent(body), - contenttype: this.configPoloApi.contenttype, - timestamp: encodeURIComponent(this._formatDate(new Date())), + const order = { + businessplat: 'OTHERS', + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode, + customercode: '', + customername: storeName || '测试', + goods: [{ + cnname, + count: String(goodsCount), + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: String(orderWeight), + price: '0.0', + }], + logisticsproductname: 'JH_02', + logistictype: cpcode, + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: sourceOrderCodeText || (sourceIdText.length > 13 ? sourceIdText.substring(0, 14) : sourceIdText), + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: sourceOrderCodeText || txLogisticID, + ProviderID: postcode === 'p03' ? 1327 : (postcode === 'p04' ? 1499 : ''), + providercode: cpcode, + receiver: { + address, + name, + area: expAreaName, + city: cityName, + mobile, + province, + }, + sender: { + country: 'CN', + Company: storeName, + address: senderAddress, + name: senderName, + area: senderArea, + town: senderTown, + city: senderCityName, + phone: senderTel, + mobile: senderTel, + tel: senderTel, + province: provinceName, + }, + shipperno: ['p22', 'p35', 'p10'].includes(postcode) ? siteCode : clientId, + sitecode: siteCode || '', + Inputsite: siteCode || '', + transtype: '0', }; - // 签名 - const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date()) }; - const signText = this.getSignText(signMap, this.configPoloApi.appSecret); - urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8'); - // 返回请求体和参数 - return { body, urlParams }; - } + if (postcode === 'p10') { + const pickupDate = new Date(); + pickupDate.setDate(pickupDate.getDate() + 3); + const pickupEndDate = new Date(); + pickupEndDate.setDate(pickupEndDate.getDate() + 4); + const pad = value => (value < 10 ? `0${value}` : String(value)); + order.pickUpDate = `${pickupDate.getFullYear()}-${pad(pickupDate.getMonth() + 1)}-${pad(pickupDate.getDate())} 18:00:00`; + order.pickUpEndDate = `${pickupEndDate.getFullYear()}-${pad(pickupEndDate.getMonth() + 1)}-${pad(pickupEndDate.getDate())} 18:00:00`; + } - // 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑) - getJsonData(expressConfig, wmsOrder) { - // 可根据 type 判断调用 getJsonDatas 或单独组装 - return this.getJsonDatas(expressConfig, [ wmsOrder ]); - } - - // 生成签名字符串 - getSignText(signMap, secret) { - let sb = '' + secret; - Object.keys(signMap).sort().forEach(key => { - sb += key + signMap[key]; + return this.client.request({ + method, + platid, + bizcontent: { + orders: [order], + shoptype, + }, }); - sb += secret; - return sb; - } - - // MD5加密 - md5Encrypt(text, encoding = 'utf8') { - return crypto.createHash('md5').update(text, encoding).digest('hex'); - } - - // 工具:格式化日期 - _formatDate(date) { - // 仅支持 yyyy-MM-dd HH:mm:ss - const pad = n => (n < 10 ? '0' + n : n); - return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' - + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); - } - - // 工具:组装取件日期 - _formatPickupDate(year, month, day) { - const pad = n => (n < 10 ? '0' + n : n); - return `${year}-${pad(month)}-${pad(day)} 18:00:00`; } } diff --git a/app/service/systems/qimen_query.js b/app/service/systems/qimen_query.js index 602932e..38c7f2c 100644 --- a/app/service/systems/qimen_query.js +++ b/app/service/systems/qimen_query.js @@ -86,11 +86,24 @@ class QimenQueryService extends Service { const separator = baseUrl.includes('?') ? '&' : '?'; return `${baseUrl}${separator}${queryString}`; } - async sendRequest(url, requestData) { + /** + * 发送奇门请求并在成功或失败时落库日志。 + * @param {string} url 请求地址。 + * @param {string} requestData 请求报文。 + * @param {Object} [logData={}] 日志基础数据。 + * @return {Promise<{queryId: *, res: string}>} 请求结果。 + */ + async sendRequest(url, requestData, logData = {}) { const startTime = Date.now(); const { service } = this; - const logData = {}; - logData.body = requestData; + const requestLogData = Object.assign({ + body: requestData, + result: '', + log_id: this.ctx.qimenLogId || null, + }, logData); + requestLogData.body = requestLogData.body || requestData; + requestLogData.result = requestLogData.result || ''; + requestLogData.log_id = requestLogData.log_id || this.ctx.qimenLogId || null; let httpquery = null; if (url.indexOf('https://') > -1) { httpquery = https; @@ -117,6 +130,8 @@ class QimenQueryService extends Service { throw new Error('XML内容为空'); } } catch (error) { + requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`; + await service.qimen.saveQimenLog(requestLogData, startTime); throw error; } const header = { @@ -128,26 +143,39 @@ class QimenQueryService extends Service { method: 'POST', headers: header, }; - const res = await new Promise((resolve, reject) => { - const req = httpquery.request(url, options, response => { - let datas = ''; - response.on('data', chunk => { - datas += chunk; - }); - response.on('end', () => { - resolve(datas); - }); - }); + let res; + try { + res = await new Promise((resolve, reject) => { + let req; + try { + req = httpquery.request(url, options, response => { + let datas = ''; + response.on('data', chunk => { + datas += chunk; + }); + response.on('end', () => { + resolve(datas); + }); + }); + } catch (error) { + reject(error); + return; + } - req.on('error', error => { - reject(error); - }); + req.on('error', error => { + reject(error); + }); - req.write(requestXml); - req.end(); - }); - logData.result = res; - const queryId = await service.qimen.saveQimenLog(logData, startTime); + req.write(requestXml); + req.end(); + }); + } catch (error) { + requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`; + await service.qimen.saveQimenLog(requestLogData, startTime); + throw error; + } + requestLogData.result = res; + const queryId = await service.qimen.saveQimenLog(requestLogData, startTime); return { queryId, res }; } } diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 7819a62..609049d 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -2181,6 +2181,20 @@ class stockStoreService extends Service { } } + /** + * 获取仓库商品详情。 + * + * @param {object} data - 查询参数。 + * @param {number|string} data.id - 商品 ID。 + * @return {Promise} 商品详情。 + */ + /** + * 查询库存商品详情。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.id 库存商品 ID。 + * @return {Promise} 库存商品详情。 + */ async getInfo(data) { const { ctx, @@ -2223,6 +2237,10 @@ class stockStoreService extends Service { 'box_width', 'box_height', 'box_volume', + 'inbound_min_days', + 'outbound_min_days', + 'remaining_threshold_days', + 'shelf_life_days', 'store_id', ], raw: true, @@ -2230,6 +2248,12 @@ class stockStoreService extends Service { stock.enable_box_spec = !!stock.enable_box_spec; return stock; } + /** + * 更新仓库商品资料,并在启用保质期管理时校验保质期相关字段。 + * + * @param {Object} data 请求体,包含商品主键及待更新字段。 + * @return {Promise} 返回更新后的商品详情。 + */ async saveWarehouseStock(data) { const { ctx, service } = this; const warehouseId = ctx.user.store_id; @@ -2242,11 +2266,25 @@ class stockStoreService extends Service { enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, box_width, box_height, box_volume, box_remark, id, + shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, } = data; const prohibited_id_tmp = !prohibited_id ? null : parseInt(prohibited_id); // 1. 参数验证 this.validateSaveParams(data); + if (is_shelf_life_mgmt === 'Y') { + const shelfLifeFields = [ + [ 'shelf_life_days', shelf_life_days ], + [ 'inbound_min_days', inbound_min_days ], + [ 'outbound_min_days', outbound_min_days ], + [ 'remaining_threshold_days', remaining_threshold_days ], + ]; + const invalidShelfLifeFields = shelfLifeFields.filter(item => Number(item[1]) <= 0); + if (invalidShelfLifeFields.length > 0) { + throw new Error('启用保质期管理时,shelf_life_days、inbound_min_days、outbound_min_days、remaining_threshold_days 都必须存在且大于 0'); + } + } + let transaction; try { // 2. 开启事务 @@ -2265,7 +2303,6 @@ class stockStoreService extends Service { if (!stock_info) { throw new Error('商品不存在'); } - // 4. 准备更新数据 const updateData = { item_code, @@ -2297,6 +2334,10 @@ class stockStoreService extends Service { box_height, box_volume, box_remark, + shelf_life_days, + inbound_min_days, + outbound_min_days, + remaining_threshold_days, updated_at: new Date(), }; // 5. 清除空值 @@ -2715,6 +2756,15 @@ class stockStoreService extends Service { }); return { message: '删除成功', code: 200 }; } + /** + * 快捷搜索仓库商品并补全库存管理标记。 + * @param {Object} data 请求体 + * @param {string} [data.keyword] 搜索关键字 + * @param {number|string} [data.store_id] 货主ID + * @param {boolean} [data.with_stock=false] 是否返回关联库存数据 + * @param {boolean} [data.is_batch=false] with_stock=true 时是否按批次返回 + * @return {Promise} 搜索结果,data 为商品数组 + */ async search(data) { const { keyword, store_id = null, with_stock = false, is_batch = false } = data; const { ctx, app } = this; @@ -2789,6 +2839,10 @@ class stockStoreService extends Service { 'id', 'item_code', 'goods_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity', 'brand_name', 'item_type', + 'inbound_min_days', 'outbound_min_days', + 'shelf_life_days', 'remaining_threshold_days', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', ], order: [[ 'create_at', 'DESC' ]], limit: 50, @@ -2802,6 +2856,16 @@ class stockStoreService extends Service { // 提取所有条形码 result.barcodes = result.barcodes?.map(b => b.barcode) || []; + const batchMgmtValue = result.is_batch_mgmt; + result.is_batch_mgmt_enabled = typeof batchMgmtValue === 'boolean' + ? batchMgmtValue + : [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(batchMgmtValue).trim().toUpperCase()); + delete result.is_batch_mgmt; + + const shelfLifeMgmtValue = result.is_shelf_life_mgmt; + result.is_shelf_life_mgmt = typeof shelfLifeMgmtValue === 'boolean' + ? shelfLifeMgmtValue + : [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(String(shelfLifeMgmtValue).trim().toUpperCase()); return result; }); diff --git a/app/service/systems/storage/expiry.js b/app/service/systems/storage/expiry.js new file mode 100644 index 0000000..6048951 --- /dev/null +++ b/app/service/systems/storage/expiry.js @@ -0,0 +1,199 @@ +'use strict'; + +const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * 库存有效期列表服务。 + * 以库存记录为主表,关联商品资料后按当前仓库与效期阈值规则分页查询。 + */ +class StorageExpiryService extends Service { + /** + * 查询库存有效期预警列表。 + * + * @param {Object} [where={}] 查询条件 + * @param {Object} [pageParams={}] 分页参数 + * @param {number} [pageParams.page=1] 当前页码 + * @param {number} [pageParams.pageSize=20] 每页条数 + * @return {Promise} 查询结果 + */ + async list(where = {}, pageParams = {}) { + const { ctx, app } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + + if (!warehouseId) { + return { + code: 400, + message: '当前用户未绑定仓库', + data: { + list: [], + pagination: { + page: 1, + pageSize: 20, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }, + }; + } + + const page = Math.max(Number(pageParams.page) || 1, 1); + const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1); + const offset = (page - 1) * pageSize; + const { Op, literal } = app.Sequelize; + + const specialFieldMap = { + item_code: { + bucket: 'stock', + }, + goods_code: { + bucket: 'stock', + }, + item_name: { + bucket: 'stock', + }, + sku_property: { + bucket: 'stock', + }, + stock_unit: { + bucket: 'stock', + }, + is_shelf_life_mgmt: { + bucket: 'stock', + field: 'is_shelf_life_mgmt', + }, + remaining_threshold_days: { + bucket: 'stock', + }, + }; + + const parsed = ctx.whereParsed && Array.isArray(ctx.whereParsed.dynamicConditions) + ? ctx.whereParsed + : parseWhereConditions({ + where, + app, + specialFieldMap, + }).result; + + const dynamicConditions = Array.isArray(parsed.dynamicConditions) + ? parsed.dynamicConditions + : []; + const stockConditions = Array.isArray(parsed.bucketConditions && parsed.bucketConditions.stock) + ? parsed.bucketConditions.stock + : []; + + const storageWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + { is_enabled: 1 }, + { delete_at: null }, + { quantity: { [Op.gt]: 0 } }, + { expiry_date: { [Op.ne]: null } }, + literal('DATEDIFF(`wms_storage`.`expiry_date`, CURDATE()) <= `stock`.`remaining_threshold_days`'), + ], + }; + + if (dynamicConditions.length > 0) { + storageWhere[Op.and].push({ [Op.and]: dynamicConditions }); + } + + const stockWhere = { + [Op.and]: [ + { is_valid: 'Y' }, + { delete_at: null }, + { warehouse_id: warehouseId }, + { is_shelf_life_mgmt: 'Y' }, + { remaining_threshold_days: { [Op.gt]: 0 } }, + ], + }; + + if (stockConditions.length > 0) { + stockWhere[Op.and].push({ [Op.and]: stockConditions }); + } + + const { count, rows } = await ctx.model.Storage.findAndCountAll({ + where: storageWhere, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + required: true, + attributes: [ + 'id', + 'item_code', + 'goods_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'store_id', + 'warehouse_id', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + where: stockWhere, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + required: false, + attributes: [ 'id', 'space_code', 'custom_name' ], + }, + ], + order: [ + [ 'expiry_date', 'ASC' ], + [ 'inbound_time', 'ASC' ], + [ 'id', 'ASC' ], + ], + offset, + limit: pageSize, + distinct: true, + subQuery: false, + }); + + const now = Date.now(); + const list = rows.map(row => { + const plain = row.get({ plain: true }); + const expiryTime = plain.expiry_date ? new Date(plain.expiry_date).getTime() : null; + const thresholdDays = Number(plain.stock && plain.stock.remaining_threshold_days) || 0; + const remainingDays = expiryTime === null || Number.isNaN(expiryTime) + ? null + : Math.max(0, Math.ceil((expiryTime - now) / DAY_MS)); + + return { + ...plain, + threshold_days: thresholdDays, + remaining_days: remainingDays, + is_expired: expiryTime !== null && !Number.isNaN(expiryTime) ? expiryTime < now : false, + created_at: plain.created_at ? app.formatDate(plain.created_at) : null, + updated_at: plain.updated_at ? app.formatDate(plain.updated_at) : null, + inbound_time: plain.inbound_time ? app.formatDate(plain.inbound_time) : null, + production_date: plain.production_date ? app.formatDate(plain.production_date) : null, + expiry_date: plain.expiry_date ? app.formatDate(plain.expiry_date) : null, + }; + }); + + const totalPages = pageSize > 0 ? Math.ceil(count / pageSize) : 0; + + return { + code: 200, + message: '查询成功', + data: { + list, + pagination: { + page, + pageSize, + total: count, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }, + }; + } +} + +module.exports = StorageExpiryService; diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 1e63294..148d35c 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -1,6 +1,204 @@ 'use strict'; const Service = require('egg').Service; +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * 计算库存批次的保质期预警状态。 + * + * @param {Object} stock 商品库存资料 + * @param {string|Date|null} expiryDate 批次到期日期 + * @param {number} [nowMs=Date.now()] 当前时间戳 + * @return {{remainingDays: (number|null), isTriggered: boolean}} 预警信息 + */ +function getShelfLifeWarningState(stock = {}, expiryDate = null, nowMs = Date.now()) { + const expiryTime = expiryDate ? new Date(expiryDate).getTime() : null; + const remainingDays = expiryTime === null || Number.isNaN(expiryTime) + ? null + : Math.max(0, Math.ceil((expiryTime - nowMs) / DAY_MS)); + const isShelfLifeMgmt = stock.is_shelf_life_mgmt === 'Y' || stock.is_shelf_life_mgmt === true; + const thresholdDays = Number(stock.remaining_threshold_days) || 0; + + return { + remainingDays, + isTriggered: Boolean(isShelfLifeMgmt && thresholdDays > 0 && remainingDays !== null && remainingDays <= thresholdDays), + }; +} + +/** + * 将库存商品上的标记值规范化为布尔值。 + * + * @param {unknown} value 待转换的标记值 + * @return {boolean} 是否为真值 + */ +function toBooleanFlag(value) { + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + if (typeof value === 'string') { + return [ 'Y', '1', 'TRUE', 'T', 'YES' ].includes(value.trim().toUpperCase()); + } + + return false; +} + +/** + * 将模型查询结果转换为普通对象。 + * + * @param {unknown} record 模型记录或普通对象 + * @return {Object|null} 普通对象 + */ +function toPlainRecord(record) { + if (!record) { + return null; + } + + if (typeof record.get === 'function') { + return record.get({ plain: true }); + } + + return record; +} + +/** + * 批量加载库存商品的条码与图片附属信息。 + * + * @param {Object} ctx 当前请求上下文 + * @param {number[]} stockIds 商品ID列表 + * @return {Promise<{barcodesByStockId: Map, imagesByStockId: Map}>} 附属信息映射 + */ +async function loadStockAttachments(ctx, stockIds = []) { + const uniqueStockIds = [ ...new Set( + Array.isArray(stockIds) + ? stockIds.map(item => Number(item)).filter(Boolean) + : [] + ) ]; + + const barcodesByStockId = new Map(); + const imagesByStockId = new Map(); + + if (!uniqueStockIds.length) { + return { barcodesByStockId, imagesByStockId }; + } + + const hasStockBarcodeModel = ctx.model && ctx.model.StockBarcode && typeof ctx.model.StockBarcode.findAll === 'function'; + if (hasStockBarcodeModel) { + try { + const barcodeRows = await ctx.model.StockBarcode.findAll({ + where: { + stock_id: { + [ctx.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + + for (const item of barcodeRows || []) { + const row = toPlainRecord(item); + if (!row) { + continue; + } + + const stockId = Number(row.stock_id); + const barcode = row.barcode ? String(row.barcode) : ''; + if (!stockId || !barcode) { + continue; + } + + if (!barcodesByStockId.has(stockId)) { + barcodesByStockId.set(stockId, []); + } + + barcodesByStockId.get(stockId).push(barcode); + } + } catch (error) { + ctx.logger?.warn?.('[storage.inventory] 查询商品条码失败,已降级为空数组', { + error: error.message, + }); + } + } + + const hasFileReferenceModel = ctx.model && ctx.model.FileReference && typeof ctx.model.FileReference.findAll === 'function'; + const hasFileModel = Boolean(ctx.model && ctx.model.File); + if (hasFileReferenceModel && hasFileModel) { + try { + const imageRows = await ctx.model.FileReference.findAll({ + where: { + business_type: 'stock', + business_id: { + [ctx.app.Sequelize.Op.in]: uniqueStockIds, + }, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + }); + + for (const item of imageRows || []) { + const row = toPlainRecord(item); + if (!row) { + continue; + } + + const stockId = Number(row.business_id); + const imageUrl = (row.file && row.file.file_url) || row.file_url || row.url || row.file_path || ''; + if (!stockId || !imageUrl) { + continue; + } + + if (!imagesByStockId.has(stockId)) { + imagesByStockId.set(stockId, []); + } + + imagesByStockId.get(stockId).push(String(imageUrl)); + } + } catch (error) { + ctx.logger?.warn?.('[storage.inventory] 查询商品图片失败,已降级为空数组', { + error: error.message, + }); + } + } + + return { + barcodesByStockId, + imagesByStockId, + }; +} + +/** + * 为库存列表补充商品附属信息。 + * + * @param {Object} ctx 当前请求上下文 + * @param {Object[]} list 库存列表 + * @return {Promise} + */ +async function enrichInventoryStockAttachments(ctx, list = []) { + const stockIds = list.map(item => Number(item?.stock?.id || item?.stock_id || 0)).filter(Boolean); + const { barcodesByStockId, imagesByStockId } = await loadStockAttachments(ctx, stockIds); + + for (const item of list) { + const stockId = Number(item?.stock?.id || item?.stock_id || 0); + if (!stockId) { + continue; + } + + if (!item.stock) { + item.stock = {}; + } + + item.stock.barcodes = barcodesByStockId.get(stockId) || []; + item.stock.images = imagesByStockId.get(stockId) || []; + } +} class InventoryService extends Service { @@ -169,7 +367,9 @@ class InventoryService extends Service { // 5c. 写入/更新 wms_storage 库存位置表 const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 - const batchNo = detail.batch_number || receiving.receiving_number || entryOrderCode; + const batchNo = String(detail.batch_number || '').trim() || String(receiving.receiving_number || '').trim() || entryOrderCode; + const productionDate = detail.production_date || null; + const expiryDate = detail.expiry_date || null; const inventoryType = 'ZP'; // 默认正品 // 查找是否已有相同 库位+SKU+批次+类型 的库存记录 @@ -192,6 +392,10 @@ class InventoryService extends Service { quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), entry_order_id: entryOrder.id, + batch_no: batchNo, + production_date: productionDate, + expiry_date: expiryDate, + updated_at: new Date(), }, { where: { id: storageRecord.id }, transaction, @@ -208,8 +412,8 @@ class InventoryService extends Service { quantity: inboundQty, locked_quantity: 0, available_quantity: inboundQty, - production_date: detail.production_date || null, - expiry_date: detail.expiry_date || null, + production_date: productionDate, + expiry_date: expiryDate, inbound_time: new Date(), inbound_order_no: entryOrderCode, receiving_id: receivingId, @@ -1730,14 +1934,24 @@ class InventoryService extends Service { } /** - * 库存列表查询。 - * @param {Object} pageParams 分页参数 - * @param {Object} sortParams 排序参数 - * @param {boolean} groupByBatch 是否按批次 + * 查询库存列表。 + * + * 支持按批次明细或合并模式返回库存,并补充商品条码、图片附件、保质期预警和货主名称。 + * 货主名称来源于货主签约表的 store_remask 字段,最终以 stock.store_name 输出。 + * + * @param {Object} [pageParams={}] 分页参数 + * @param {number} [pageParams.page=1] 页码 + * @param {number} [pageParams.pageSize=20] 每页数量 + * @param {Object} [sortParams={}] 排序参数 + * @param {string} [sortParams.sortField='created_at'] 排序字段 + * @param {string} [sortParams.sortOrder='DESC'] 排序方向 + * @param {boolean} [groupByBatch=false] 是否按批次明细返回 + * @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果 */ async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; + const nowMs = Date.now(); const warehouseId = ctx.user.store_id; const { page = 1, pageSize = 20 } = pageParams; @@ -1772,7 +1986,24 @@ class InventoryService extends Service { { model: ctx.model.StockWarehouse, as: 'stock', - attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'store_stock', + attributes: [ 'store_id', 'store_remask' ], + required: false, + }, + ], required: false, }, { @@ -1786,14 +2017,24 @@ class InventoryService extends Service { const list = rows.map(item => { const row = item.get({ plain: true }); + const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); + if (row.stock) { + row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); + row.stock.store_name = row.stock.store_stock?.store_remask || null; + delete row.stock.store_stock; + delete row.stock.is_batch_mgmt; + } row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; + row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; return row; }); + await enrichInventoryStockAttachments(ctx, list); + return { list, pagination: { @@ -1822,6 +2063,8 @@ class InventoryService extends Service { 'inventory_type', 'warehouse_id', 'store_id', + [ fn('MIN', col('wms_storage.production_date')), 'production_date' ], + [ fn('MIN', col('wms_storage.expiry_date')), 'expiry_date' ], [ fn('SUM', col('wms_storage.quantity')), 'quantity' ], [ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ], [ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ], @@ -1837,7 +2080,24 @@ class InventoryService extends Service { { model: ctx.model.StockWarehouse, as: 'stock', - attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + attributes: [ + 'id', + 'item_code', + 'item_name', + 'sku_property', + 'stock_unit', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'remaining_threshold_days', + ], + include: [ + { + model: ctx.model.StoreWarehouse, + as: 'store_stock', + attributes: [ 'store_id', 'store_remask' ], + required: false, + }, + ], required: false, }, { @@ -1852,11 +2112,23 @@ class InventoryService extends Service { }); const list = rows.map(row => { + const shelfLifeWarningState = getShelfLifeWarningState(row.stock || {}, row.expiry_date, nowMs); + if (row.stock) { + row.stock.is_batch_mgmt_enabled = toBooleanFlag(row.stock.is_batch_mgmt); + row.stock.store_name = row.stock.store_stock?.store_remask || null; + delete row.stock.store_stock; + delete row.stock.is_batch_mgmt; + } row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : ''; row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : ''; + row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; + row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; + row.is_shelf_life_warning_triggered = shelfLifeWarningState.isTriggered; return row; }); + await enrichInventoryStockAttachments(ctx, list); + return { list, pagination: { diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index cce6937..c2086f7 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2,6 +2,15 @@ const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); +const DAY_MS = 24 * 60 * 60 * 1000; + +function getStartOfDayMs(value) { + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + date.setHours(0, 0, 0, 0); + return date.getTime(); +} + class ReceivingService extends Service { /** * 查询收货单列表。 @@ -2763,6 +2772,21 @@ class ReceivingService extends Service { 'box_quantity', 'pallet_quantity', 'receiving_status', 'storage_status', 'batch_number', 'production_date', 'expiry_date', 'remark', ], + include: [{ + model: ctx.model.StockWarehouse, + as: 'system_product', + required: false, + attributes: [ + 'id', + 'item_name', + 'item_code', + 'is_batch_mgmt', + 'is_shelf_life_mgmt', + 'inbound_min_days', + 'shelf_life_days', + 'remaining_threshold_days', + ], + }], }], }); @@ -2821,6 +2845,80 @@ class ReceivingService extends Service { }; } + const batchManagedDetails = receiving.details.filter(detail => detail.system_product && detail.system_product.is_batch_mgmt === 'Y'); + const missingBatchNumberDetails = batchManagedDetails.filter(detail => !String(detail.batch_number || '').trim()); + + if (missingBatchNumberDetails.length > 0) { + await transaction.rollback(); + return { + success: false, + code: 'BATCH_NUMBER_REQUIRED', + message: '批次管理商品必须填写批次号', + data: { + invalid_details: missingBatchNumberDetails.map(detail => ({ + detail_id: detail.id, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + })), + }, + }; + } + + const missingBatchDetails = batchManagedDetails.filter(detail => !detail.production_date || !detail.expiry_date); + + if (missingBatchDetails.length > 0) { + await transaction.rollback(); + return { + success: false, + code: 'PRODUCTION_DATE_REQUIRED', + message: '批次管理商品必须填写生产日期和有效期', + data: { + invalid_details: missingBatchDetails.map(detail => ({ + detail_id: detail.id, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + })), + }, + }; + } + + const todayStartMs = getStartOfDayMs(new Date()); + const invalidExpiryDetails = batchManagedDetails.filter(detail => { + const minReceiveDays = Number(detail.system_product?.inbound_min_days) || 0; + if (minReceiveDays <= 0) return false; + + const expiryTime = new Date(detail.expiry_date).getTime(); + if (Number.isNaN(expiryTime)) return false; + + return (expiryTime - (minReceiveDays * DAY_MS)) < todayStartMs; + }); + + if (invalidExpiryDetails.length > 0) { + await transaction.rollback(); + const firstInvalid = invalidExpiryDetails[0]; + const minReceiveDays = Number(firstInvalid.system_product?.inbound_min_days) || 0; + + return { + success: false, + code: 'EXPIRY_DATE_TOO_SOON', + message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`, + data: { + invalid_details: invalidExpiryDetails.map(detail => ({ + detail_id: detail.id, + item_name: detail.product_name || detail.system_product?.item_name || '未命名商品', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + inbound_min_days: Number(detail.system_product?.inbound_min_days) || 0, + })), + }, + }; + } + // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求) const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); diff --git a/app/service/systems/store.js b/app/service/systems/store.js index 0b8291c..4e4cc47 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -10,6 +10,8 @@ class StoreService extends Service { return { max_notice_webhook_count: 5, + default_express_code: 'STO', + default_platform_code: 'TB', }; } diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 61c15fb..2b5aa8e 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -257,6 +257,19 @@ class SettingStoreWarehouseService extends Service { return storeWarehouseModel.getPolicyConfigFieldList(); } + /** + * 获取带动态选项的策略配置字段清单。 + * + * @return {Promise} 策略配置字段数组。 + */ + async getPolicyConfigFieldMetaList() { + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldListWithOptions !== 'function') { + return this.getPolicyConfigFieldList(); + } + return storeWarehouseModel.getPolicyConfigFieldListWithOptions(); + } + /** * 规范化策略配置内容。 * @@ -1711,7 +1724,7 @@ class SettingStoreWarehouseService extends Service { async getPolicyConfigFields() { return { code: 200, - data: this.getPolicyConfigFieldList(), + data: await this.getPolicyConfigFieldMetaList(), }; } diff --git a/config/plugin.js b/config/plugin.js index a827fec..f7f051c 100644 --- a/config/plugin.js +++ b/config/plugin.js @@ -15,8 +15,10 @@ module.exports = { package: 'egg-jwt', }, sequelize: { - // disable real database connection during unit tests - enable: process.env.NODE_ENV !== 'test', + // disable real database connection during unit tests unless opt-in (see order_delivery_dispatch_factory.test.js) + enable: + process.env.NODE_ENV !== 'test' || + process.env.DISPATCH_FACTORY_TEST_MYSQL === '1', package: 'egg-sequelize', }, cors: { diff --git a/config/poloapi.js b/config/poloapi.js deleted file mode 100644 index 934c491..0000000 --- a/config/poloapi.js +++ /dev/null @@ -1,29 +0,0 @@ -// config/poloapi.js -// 快手/PolyAPI相关固定配置 - -module.exports = { - appKey: '8e770a60b9684c558f40e4796a96710f', - appSecret: 'c9cb1df531b441a8872c60ffb7f900a6', - platid: '633', - version: '1.5', - contenttype: 'json', - urls: 'https://api.polyapi.com/openapi/do', - // 快递公司代码映射 - postCodeMap: { - p01: 'YTO', - p02: 'STO', - p03: 'YUNDA', - p04: 'ZTO', - p05: 'SF', - p06: 'TTKDEX', - p07: 'EMS', - p10: 'JD', - p22: 'POSTB', - p35: 'POST_DSBK', - p09: 'huitongkuaidi', - p26: 'debangwuliu', - p32: 'JT', - p34: 'FENGWANG', - }, - // 如有更多固定配置,可继续补充 -}; diff --git a/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js b/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js index 6f06972..9af7483 100644 --- a/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js +++ b/database/migrations/20260410130000-add-audit-status-to-order-delivery-tables.js @@ -5,7 +5,7 @@ module.exports = { * 为发货单主表及分表新增 audit_status 字段。 * 若存在 inspection_status,则将 audit_status 放在其后;否则按默认位置新增,保证兼容旧库结构。 * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async up(queryInterface) { const [ tables ] = await queryInterface.sequelize.query(` @@ -54,7 +54,7 @@ module.exports = { * 回滚删除发货单主表及分表的 audit_status 字段。 * 仅在字段存在时删除,保证回滚幂等且安全。 * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async down(queryInterface) { const [ tables ] = await queryInterface.sequelize.query(` @@ -85,4 +85,4 @@ module.exports = { } } }, -}; \ No newline at end of file +}; diff --git a/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js b/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js index d6955a0..96fda06 100644 --- a/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js +++ b/database/migrations/20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js @@ -48,7 +48,7 @@ module.exports = { * 为发货单主表及分表新增 step 字段,并从 audit_status 回填后删除 audit_status。 * * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async up(queryInterface) { const tables = await findOrderDeliveryTables(queryInterface); @@ -86,7 +86,7 @@ module.exports = { * 回滚恢复 audit_status 字段,并根据 step 回填后删除 step。 * * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 - * @returns {Promise} 无返回值。 + * @return {Promise} 无返回值。 */ async down(queryInterface) { const tables = await findOrderDeliveryTables(queryInterface); diff --git a/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js b/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js index 1e29cdb..86bfa5a 100644 --- a/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js +++ b/database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js @@ -79,10 +79,10 @@ const STATUS_MACHINE_COLUMNS = [ ]; /** - * @param {import('sequelize').QueryInterface} queryInterface - * @param {string} tableName - * @param {string} columnName - * @return {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @param {string} columnName 字段名。 + * @return {Promise} 是否存在指定字段。 */ async function hasColumn(queryInterface, tableName, columnName) { const [ columns ] = await queryInterface.sequelize.query( @@ -99,9 +99,9 @@ async function hasColumn(queryInterface, tableName, columnName) { } /** - * @param {import('sequelize').QueryInterface} queryInterface - * @param {string} tableName - * @return {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @return {Promise} 数据表是否存在。 */ async function tableExists(queryInterface, tableName) { const [ rows ] = await queryInterface.sequelize.query( @@ -117,10 +117,10 @@ async function tableExists(queryInterface, tableName) { } /** - * @param {import('sequelize').QueryInterface} queryInterface - * @param {string} tableName - * @param {string} preferredAfter - * @return {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @param {string} tableName 数据表名。 + * @param {string} preferredAfter 优先追加到其后的字段名。 + * @return {Promise} 可直接拼接到 SQL 中的 AFTER 片段,或空字符串。 */ async function resolveAfterClause(queryInterface, tableName, preferredAfter) { if (preferredAfter && (await hasColumn(queryInterface, tableName, preferredAfter))) { @@ -133,8 +133,8 @@ module.exports = { /** * 仅为基表 `wms_order_delivery` 按需补状态机相关列;已存在则跳过。 * - * @param {import('sequelize').QueryInterface} queryInterface - * @returns {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 */ async up(queryInterface) { if (!(await tableExists(queryInterface, TABLE))) { @@ -155,8 +155,8 @@ module.exports = { /** * 逆序删除本文件声明的状态机列(若存在)。见文件头注释。 * - * @param {import('sequelize').QueryInterface} queryInterface - * @returns {Promise} + * @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。 + * @return {Promise} 无返回值。 */ async down(queryInterface) { if (!(await tableExists(queryInterface, TABLE))) { diff --git a/database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js b/database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js new file mode 100644 index 0000000..b31ef51 --- /dev/null +++ b/database/migrations/20260415000000-init-wms-store-subject-config-default-codes.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_store + SET subject_config = JSON_INSERT( + COALESCE(subject_config, JSON_OBJECT()), + '$.default_express_code', 'STO', + '$.default_platform_code', 'TB' + ) + `); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store` LIKE 'subject_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.sequelize.query(` + UPDATE wms_store + SET subject_config = JSON_REMOVE(subject_config, '$.default_express_code', '$.default_platform_code') + WHERE subject_config IS NOT NULL + `); + }, +}; \ No newline at end of file diff --git a/database/migrations/20260415172000-create-wms-express-interface.js b/database/migrations/20260415172000-create-wms-express-interface.js new file mode 100644 index 0000000..6067297 --- /dev/null +++ b/database/migrations/20260415172000-create-wms-express-interface.js @@ -0,0 +1,74 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { INTEGER, STRING } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_express_interface'" + ); + + if (tables.length > 0) { + console.log('Table wms_express_interface already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_express_interface', { + id: { + type: INTEGER(10), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '接口ID', + }, + interface_url: { + type: STRING(500), + allowNull: false, + comment: '外部接口URL', + }, + platform_code: { + type: STRING(50), + allowNull: false, + comment: '平台代码,用于应用分流', + }, + interface_name: { + type: STRING(200), + allowNull: false, + comment: '接口名称', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '快递外部接口配置表', + }); + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_express_interface', [ 'platform_code' ], { + name: 'idx_platform_code', + }); + + await safeCreateIndex('wms_express_interface', [ 'interface_name' ], { + name: 'idx_interface_name', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_express_interface'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_express_interface'); + } + }, +}; \ No newline at end of file diff --git a/database/migrations/20260415190000-create-wms-picking.js b/database/migrations/20260415190000-create-wms-picking.js new file mode 100644 index 0000000..363949d --- /dev/null +++ b/database/migrations/20260415190000-create-wms-picking.js @@ -0,0 +1,118 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, DATE } = Sequelize; + const tableName = 'wms_picking'; + + const [ tables ] = await queryInterface.sequelize.query( + `SHOW TABLES LIKE '${tableName}'` + ); + + if (tables.length === 0) { + await queryInterface.createTable(tableName, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单ID', + }, + order_item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '订单明细ID', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库存记录ID', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + space_name: { + type: STRING(100), + allowNull: true, + comment: '库位名称', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单储位分配表', + }); + } else { + console.log('Table wms_picking already exists, ensuring indexes'); + } + + const safeCreateIndex = async (fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex([ 'order_id' ], { + name: 'idx_wms_picking_order_id', + }); + + await safeCreateIndex([ 'order_item_id' ], { + name: 'idx_wms_picking_order_item_id', + }); + + await safeCreateIndex([ 'storage_id' ], { + name: 'idx_wms_picking_storage_id', + }); + + await safeCreateIndex([ 'space_id' ], { + name: 'idx_wms_picking_space_id', + }); + + await safeCreateIndex([ 'status' ], { + name: 'idx_wms_picking_status', + }); + + await safeCreateIndex([ 'order_item_id', 'space_id' ], { + name: 'idx_wms_picking_order_item_space', + }); + }, + + async down(queryInterface) { + const tableName = 'wms_picking'; + const [ tables ] = await queryInterface.sequelize.query( + `SHOW TABLES LIKE '${tableName}'` + ); + + if (tables.length > 0) { + await queryInterface.dropTable(tableName); + } + }, +}; diff --git a/database/migrations/20260415191000-add-quantity-to-wms-picking.js b/database/migrations/20260415191000-add-quantity-to-wms-picking.js new file mode 100644 index 0000000..39b9ebb --- /dev/null +++ b/database/migrations/20260415191000-add-quantity-to-wms-picking.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableName = 'wms_picking'; + const { INTEGER } = Sequelize; + + const [ quantityColumns ] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'quantity'` + ); + + if (quantityColumns.length === 0) { + await queryInterface.addColumn(tableName, 'quantity', { + type: INTEGER(10).UNSIGNED, + allowNull: false, + defaultValue: 1, + comment: '分配数量', + }); + } + }, + + async down(queryInterface) { + const tableName = 'wms_picking'; + const [ quantityColumns ] = await queryInterface.sequelize.query( + `SHOW COLUMNS FROM \`${tableName}\` LIKE 'quantity'` + ); + + if (quantityColumns.length > 0) { + await queryInterface.removeColumn(tableName, 'quantity'); + } + }, +}; \ No newline at end of file diff --git a/day.log b/day.log deleted file mode 100644 index 2031b050e23e72ced46177106b69ae19c812d15c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 37706 zcmeI53v^v&o#^)wDT$;J=h4v!i;Z`#L?q2Ak19pD7OYTd_sKaYZ5q;?q&Yo3sY%n) zG^Z~~p;m1tEeS#&pn}{b!dmw__O5%qv$(D$=n`CL z|LuRie&0TiG)2a_t~D#G&B;D{e~f77Cwr|-=yUN$P{3%GR7f7(X^5_5a*s|H|jWQGKT`MbR&P0-Z49U0r<$H^_52xqu=h;*1zL@#>*i)k~4?c7E z-uCl@^ZL*EmgCt|W0&^YRUNtezO?UUWM>P#k9bSv_gsO*YJquS_oDRH zL$8)}HD5?A-Scwogf{jZjm^=v2%?+3yB{@jTgaYax+8HTJ`7IZe70I#(!pz2IV%{8sApyGR;MY9z!eC$u0dH>dyG_CorlY(u#8K#*!|e`Qo@gw+oTe&GL&f+<4>7xY~| zH4hSIuTTnfhD>uM&Oa6|E<#5OcD!R{HF{CVDZQ~5=*q5MrO3x*=92sq=`nHl_{qY{ z6SFc~H~z&yN7vT|_O|HkEQ<;l!Gz&Slvf)3>a9L3j@RGrK6bZF_ZvD?OhdtrMD9 zE&D)@AQ_Na@X?7i-`;c1CwG;O6&~(`hpaUGm+{N)van|U>9`Wcdj5ujhik^ZK7ke>VU50}I!kzs*AM$IBDRY|pWX%HW;4 z@ZtPR*~Wk;p+U6|fGt`T$%Onz*Z#8S;)yS2ZXa(7RX(~@jXtQ9Dd;S;F!)77H44SW zb+7Lsof|^ddpvuh^l<*1z0D)LqWPZM^IJ!9u@ctUzZ+fjw*#+rHHClOhn(Il)H^Kl zY`x5(y09nujr>(jxmD(Fm4DUl#NJW8AHPQ>H@d+c+4r8wiuUWBmClh z;Wnhi1ru8jz1CH{&Egoz3lCsxEnEkGHwMp-e!lofuy$ipWRulL5Z@$YZIDlPH!ZTe ze8kP`gvMHA7koD$atB)5JSDm7Lh#I(|7%QfIMeaaY|M$YEy!qCTS(x#5J)$!d1|yV zc(wa2Q$zF7%(vUb^pO;lzHR zxM0V;&Wn7cNK<%i(7(Ge0PZ(+Aln<)3~h1mwUCBV+;0lI+a7cw?BYtbl48zMOOMdR zT7gMHU|?)U`&4TL|5}u$@N+Q$y}X|5ceMYTKWmRr!z!VYP0`wrLtxQeg=&7Rs-oZ- znY%W^a#Lvh1-u1(g{1fn^W=YiTI9~v^3zhmQ7xxo#HaOT6k85a?pY-|eNbRJJhi$= zp38H-H`)DK*Wuy%V*hTWJ@_i+uye3+n!;*aTRwgwIg`73PVbAo`QA+(E4r{(%15*K zZ2z6P|#k4leiXbK1Vp3T?t zyL|8bpg;Yx*!tx<0UxuJyDwc3i(glKX2|&-Hr=^H%d!iy9UWF0DEwUy&-aY3v)mnD zK^)dg9r)rMTFGp<4BOyyDZFJgfr||w;ZlS9Ecywr)8fee7Mg@-)(X#5zr#GgSng8| zR{cKafQE-_j58v#-%xpW>fVtV-Te`n*VVG^Q#8vu_;;^RCw3GPyfOIJo}YG^Z{Qyy z0+qJvj{Uc{|3d&*mfM%-2ak3A@tPlx7t*hcF4_Hq{DQ4@;q~72BIU4XuPHQ-l-rnS z86=8&E_jFyAvWcuy(iY(-f3xs7zkb|o-MQcqWv}qCVi2VBl1}#L`i-h2^Iw2#Ovw* zxiQgO7cLS%K;tDh%3i?O0=Z{iv?9FW^8+s^3@pq3(?)zGMxWRDANM_&J-WPN7)^=%NG z8as=f{&ZAUC49aha4FNhyH)m5-9KhdwE*Jx8>{7P?SV6mR}`2I$u8sk*%ITj7TM!a zWa;5+!$asl^)t>izDxV)y0tQw%fT%&np&{xg}UP^>>Jt(11ei*Vh^8LnkABPE3qXI z+g~tyeBZ8~KkaEAu~d6`@sff1{GEGl7}WXW9tf6cxi2nWTmU~_=<@{Bbh2RAAAkNL ze^&`wLmM=N5+4lkyNKE0(^z^vM|ix_pHTZ2zY`mBj`$>Cf`32_nGDr)7kZ{#N~+Ap zv&;+TeeaR{{7k>ZuS{$PkHkDrlu1{kbg9qY6lq$trp6GVXfql!HiXS1cLi|5vEuog z%~%$;I*LmPtOH-Al)EVN-Of2#o_RL^t8sLd%SZ8NTs>|rYfF{oce{Ejem`*2IFWk~ ze)0>0XgxG-V{qNBAC=tIOs9XR({jFto@Z>MhiA4@7Zb=DJe+g0?-&1go>-Q?cbQo5 z-yTgQu`fRm{avmxR~26^Sv2^^*R*_hT;+sg954?#0GQm<8WtvKvl9QxH8Nio8iyxgq+5A7x`1t0UVD zDY8-MnLE)GuKZL>+@0^@kqi1txu2vuN8tUqEN3S55z*{uDC~Y@q=iz8tOS3KwPA0o zG*qgGkG){-{tsjh7Yv8$+`wy~LjRaZFWl;j_1Z2GVq%zcBx=yy@%Sk5r#OGlilQ0B z`F)S4zAt!M8m(s_;=|36PF=Qg!Pc9ykBkzB`j|v5Q(_1E-fj0knjw~I=NUQFckqg# z=Zh{~8%YqS9;~y=ro0P0Sl`3<0+y_zTv9MbQzze`4V%JBSs}4*Sv665D?eIA$Ez#} zBIp(*4nLE-S|e<1_AG59V+{PtCE&9ImkCr{o)arNd(%eNOqArg?B;z~P$_{Mkza7| zo3R@PT^i!v{`7|LXaBtW*V%J&A6{7({=EB<)IWD!wo_w^zs^3A`uW(Cy=Elc z5%(a04)q<)_8lZ5#~zoh^m_0_T0O4w$%P|vuM1bd=XUNa$I0yWUv0%ZtIpBB_q{B# z;_2~!aIz9_nOG_wl#5$risgXAkMil)0`Xe@y03oXANv|YFk$b|Z=sKmPQ{`XhUL-?T>+K3b7{Q)xol!$X+#$d zA+em3g=-J=4M3-*9QL~lWya7LXM7x1h8C&MLjxy9znoJ#UD5Suo23!-1mBMwTADe& z4Vn4M*b9U2+JAh^g(G(nIqm3r@AfN#zWkEi#H;_g>%^VAN~v|<+0(!L;l6k6uM3Il z6aNPm_|))?A9(^q{*m!WTzJ8k--g}|r9qqB6;_e!&$H5cp(R&h``(B8-`=CPMO>Pe z-|1>VwB7d)eW+h8gYr3aG#3KMoarbA z$eDPBO6VUGu*-pElQ9DL<|i$lu1YI~zVkhZ=j% z-8uWHjom~NX?uV1`oKG=^&NOLzZiXG6uXvOnvR7uTPRtkxQ~a`3*5=C_#V~^Su-?Y zMy`;vMLYfRjul-Hl{@3|ce6E7lagUlgU zjr_qc<+rKN!6IxP`R%>O_qnU6jBRLErIN0QU?h@I*WqD_+a<|i5{Fx|TVfi)CnSDw zX|J_LOnjn}lCiO&W|tB*P5^{$tgThnZg`+Yu0uu0VN+w$D^(`Pv-NpwH_fE>PQgLz zpXNHxqieB3G#iNy_)zRhAfqD}ua7WA1pLMEhsCn6T5nj{dd-YwzQvki6eJt4(%Jab8hNSgBSbWTnPsVdNnqW0y{RTB;{@Oe_@-{1%DzbVgM#*B;2N`2L}_2i!fY)!r*s z%tBdRyTD7cP>ha+fYmi8i>0C2d8~c1<~oLrx>$(%9&ohPI4(WBINmg&H9DHR(s_|I zY6bYGcPG&c2TL~!Yz&s+3PUrj@`AnxGgR@IXMOL_Bn#^9@zmHg1wZr3{;v+(teJX9 zYQL!DQ`xds{8uA07EG;%S#*Y8@hEQ*jJQuLmCWpEY~lFRN(VE0dfwEtKwV>+#7o_J zA<1%AsWZ?FR(>xGCX{de{|cFKa$E_MtZOSu{#?W2HTTl#XEXiH1sjg}a_H^~9 zzdYI_^&a=7;fJM}o72b*&6wZTbEF;1+l;6BntIH*##XJO@j@~L^9$FnYz(Mud3||# zd{#AdwI^H%Pj;&gHX6%npq8McYfG9;B(XM=k1+SCe1Qh3UDVjghKT;5d&4PqG*;u{ zz>H(>K)VntBg3K=Y9e{8duR6L!M*9mAa{@zP|2kd<9iYbd_eNeaSor;NhZ>@G4YXa zS=Shlsd4v>Rt0WU-$2)J?ub|oBl0xT4V#_4wMxv>{=j1j*Iv0(HJqsy;wiN~>^EG) z66U%1s-QRcJPwoUPa3YqLcppnh%JLpd!3Aq|1v1!H-z9(qBydjw@EbMGX?TxTDvtn zXk9~|0SNwSPa(?Wx$~-3+bg4~1x1BdHM`c`L5ti=JZeMqKN*(76wHPNE-ELDkEs>{ zHoaD-u-eG4lgfZv`M0Fx-z;wNp5qm}`kacZ2`NVxX;xSvpmdRG=k>FLDcS_-Pt_S7+{fX z7u(+5@vEu)0DLo32otx2ekylH{o}}?uN1t$z$@>Kb^-szEedGV#j;9VXm*3xIaG5} z&)p(+0Wf4I#xFFV-h3Lcv%Jx$ow>g z_FjDH=8=Guh6bmu4^nqB{7nHvipk} zs$8buBT^4r7mEY96w>$Ptb_x`M5yqZT}jp(^Pkm5Vovsbp|ARGsld?0;>3~`Oo3Oo zzrn!X_mG?Q;YEI9aG}3Ys9}SQh3!Q4u`ax6@LGwrU*yO4UE5l-D{;q4cKmjEUHHz_ z&1vZkNikkSNZiKMSz*7Ct!WInXWOB12M*^B&DuonygVa2*?ns3>H}!7r^nCVrgxCZ zGIm6{l&h?fQ)(izV4&#kQpfkCvqAjG@g=*#Qk>pdQA0?K11n`gux;D1;PI&99f~0? zspF~bMrC{4b`$Gf;^_D&Ur#?T)tLO<*bcU+gN;X5CcCvJfIBbr?UV5FMgA{)inqmS zMENNmc`Vn^eG%tttwKd!Yc7}m4@QaPBPcFaPa%Fan#ar z>ok!HSc*hDuzZOcRBAc9Ht6W8&dF}pUMNlsAsas|GTG*qO~uli4dXaI70&3@QVu`2 z8XWPSSl_>vmi>LeTXi29gPH3-umyaG2*Z6y=f?J3B`Rm&RyRUCPp~bXuH~mcc z5I9_5b~Nl{_jS9H9ZgZU3!Q&vPxu*6^xv{hWjub>g+34<{~y;vhFgieT;vml-+TZ3 z!WU9Qc~^4M9TJzE^ACJYY|X1=HJ5Mqf~|e5s9auht^7VP*A!~?iP00~aml#tK_tw2 zS;jh+2tZ_+E)?4t|3Ph+Y-F7v6Ebp*s3+R+_T0#ZOFll<5wG$ZPPgCj-01yXTC*(@n+Z>Qz2rm4<-5}PZ}x25>5fr;uU%2&1`TU@;u6OykaWAK;Qz zSh@YX&c90NhMdYKiD6=Q(MQWHW@h_6*$u7sB_5zYtHRdqN3qo^dsEuezqy;;eq8<$ zuk4Bb!s1uU+3rcPX`tVJ$D^5tx*i&%mk3EiM`FfXE>XH0y`Riu+Or^VC zT_!c~izOb5`an6|5{=?HV5=V}r7?t`(xyJgbzc1Ns zR)hsSEIb4Ek-NA~Fl43X!Yp;&bbC`ldTp=tzlGQKerJ!p1Dx^wwZY?~ua?g1|Hk+Q zeN7?QyU<4h;58i2esj+piJ#F2XrhF~B=rh0H!x0wMz0_lzdkr?la=Gf*I+jMpKR*X zCnmcu=o=GF<7N(P^`@zBGF@juJUd-mZdBf9^WavxV4G^68{L2Kjm>GX2Xq^dne5gY zCyfkcgda^l)kLr3^HIa~dir&##B23l6B~nZ5=r#v+k1c`_5{~7QbVUC)`oVUz1G$C zpw-x`BI%-D9sZKh+j?DhqTMKZg~+EHvz0nA>114T$A8#2EA#b;TjLSecZdJCG@PE( zNmLcPT%&I{b-)L970vsey&K$%C7=85HdouJH-lA=cVp$N$^=Ga|8-%dRgFJpqB`1n zx<1lj8dY@p%~Y*6g>=&czvdC~5M+f7p=)z0)ai>O_LTJO`VFOGQ#_jgv2-v^cGIS;E0p^Hd;&N zJbD8UbV0{@sq3b*`3usm%XtqP`_(>nH!9#AZ0=x8EClKT8ryGe+Zzmx+ZZ&|tGy0K z?xyR9DgwLP%eU_p%Zpwc*9Pi|^cWJx)O)A}g!Kai=<1*XwzB39Y6s7pMWIoT?`5GE zg$Y!#Fk9J0QNEs;Sc0tkjah1B{Mi^(M9(!o_e^a;m9n+0 zKK<6%J^Gimhg>@n%V~3DtDrfU-PC88r=dXb%84YAog~%a*w`+0*s;x1i$w|&2m6#% zXA%+8oLaANbv0Wwz9P+FE{tmW=%+F{U^BMbaX^gN!HV`{-Hid%j@^w-eCr)`?f78E zw}S$;ZlEdRQ;lu7)|6{qQIUY;aIaaLx6&?iuh?hZtLAASxp+HuNm$2LCa64&ET+?4 zlvY~)A^PNX;r~BYQl035TK18(+5SDZ0L@oMv+BaiT!OV67iKH_iCoEDKjp)#1R{2a zUreol9RqDN*{vFu`-4a~5*>Esr1k2xno}!Z;!?;+X*uygBFMy`rii5o$5v3qQLd zd@{JT4XXsdc-7$ZMPOl{oK8;szC4eA=P7cphDMO@7=J0mirP(YLm=UCSIdFK#%SM$sN__xAt8!fCcYM&Xov*%`7Ni$%8>!(Cp&;x*qIjy7EO#sVaw@`A-Zdi8;<51hseV{DgEu`M z-Ku|L9oE*4=UwJT&@t;e+gt(mt;VnaZS=hh)0wTkx{g=OFU(fcy;7i z)}M}G`5x8H*otx8fL~q8W&4_>-luwo_Xdft-8dzuv9ZidN^QPeaev@37pLX*Iwne| zCj*hUFCV{@BMZDV%{;f4X16b!vgO=a_{>c4IOEOfTcyg(a1j*hdoS%tY@rgHy>Xrr zcC+>@l22#|@nsv^j|4=EAIyGNxHt78j5nm-cvsrbtIo39nAgUQmM!nifv7WI_ zO;oztc;?iOxZbs%Dm7%RrTTqyr*_v6-rn9K{mImvaE=IY)V@EezO1I>95uXF_E!x9j0k`5?NBr}jpBy$JL zF=u+f5=p(+;7_qvd#(q%0ddrB% zZ<4<@ip+4KrzhlT79fr>&Y39XsGWdo$P~B{mh0pSITdRBUTO3%SdS-R~w|H7QjXzJ{zlMy-xzBW?FNDAxgYVO>X>DN`Poi)>8 zDQ6i7Tx;*EQDR)5N^_FwhuX+HZ5BuXVTCvtcQbgsM7)D*CcGgL9H)C>}iSoq~s)*MbU{zZIT&ENvG=~ z(XQ>1DPpaxNh4LJLtuKmX!ko28{&iHyYaU;38^mB9$sRZt=^^kt_`HyVB^Ad#tN;5 zubIn+rqJ!BQ|@xD4fcY)Vd8FYWH;p07@3Mp&3zL4Unnx*y3<)Qd#dl1a%Y_TiC9B9 z)LztuJ9pMkn40+Nd$(1)Ekgai_a3os`N2jhi5#MjJ1ceo{79T_sr+xUsLkG`Rb`kf zr!S2p&2|~t(LUb$re=AMtiLWq+qTNN4KEDRX^gg1YpvFb|B&M<)h)ov7)dS51bJZ2 zOhQxOHw_AOTZE&w$X|KEh^e3FbS2Ht(EA8hObrY7e^hXcU#a!lZuinkp}6X2|M1*L zV5E?<-7WQSA@ zY!po3?HW0wUN)ADuJ_HEqqS^&x^M^6x24I2vIFDYn6=2clp^6dGg8iqmRctwTYvS* zA4=?@YkU2~s^Uq>PS29_5E`Wx^u&JR9!3M``b&pySV{C=PyOhPq#e86a(cIQ64mdF zIwxI7z)eWP)(AFKS-?ZB5tnh@p2Mbg1eO=jbftM#u5n$fGu&@JA}e49b7E<`e1;~W z*u~rNYUul*dd%#`@I`&zJ9xvOdbMP2Ifw4{_Sx;*ww;h}B*ri@TlvPsO5D9+2cgdk z!Vf72`TM>-%aWH?*HDK(B_b;TabTGs7XB&+b#zac(4mp}kp|=d#L8<>#`@ zO!63>)~a-*ilN+<>HRspcivDy4T&#&%yx< zzs#3^SBm{nFYoK1O60r@-^Wk=W_9t%m%-M*R^6Nn*O}oHOHgZc-Z*u?5e&W=^UjQ` zkSPjxulSu&6P+h!Yix7XW%xxc!Jo)Eqlbr|9;dSeI>Bq^jI!HrFU9L8SNA8wt zu6C_Z`t!{FT?>N$y7^>*a{vzXJ(?-E7C4ba-{gXQ=~@KjRj@meGp3W()$Kf`_E?|D zjjQD(ool4Om9?VDz_*@%itM4spYztaIv`e%ku`XNSlwuBaIN;O!ep|W6(u8^kLT!> z0v_Z{4O}b)|M&RuZJgR5{VsAo9+3ssrq)>XZrl#>U$YXsUMe0nXD+wOs$f@3$y3Kavp7>myTvzCCEDV z29>9=Xoj4=8_rm?Rh0Jnm2$mW#S!sv>bS!5&*sInWmYRII6O3wIcOsdQzwka=1#9}LEqY$-DohWseXbyM;%c9^XrEeF zMlM@dv{+X8L0MIMG!rKpY4lSqI5S#a=+UgFd|aEG_q_(OpgRvHdhzDaev{oVE}t(J z27k}l@!32l?dmDJHa^0cH*r79dVfgZ$!@%nQjWd?xEk$w?SZev>bEqm3U|c&f;1Ye zz2&w~+PqVNl@qPec$!9K$7setAr0%K2Kvi)eKD{k=*)DtgOn4op)EQ z6Ge(uLb;^nDasp7;W8+Ikv=`ImQF8(tQqcJPmYz8m(>-O)*zrmiJgeHsuE~#h?5&+Hr(2#T zH(i*j+$2WG`*PrC_v$j)kBMT|hn(bP_o(kGV)QoIDbn5g&vRqY;K}LXLH)s7J6%e^ z!p3e_O=jwCdSrFlfy1iw%^pZ`BoQa;Xdhu+bOQhJ?5%CBk`v>1BKee@L{FD%B8eZ4 z2F>*3R>ozL>4zwvlkO+^gln!=+QxQ7aHsMXGk&Z#_6#Oe(!7@n*=Nkr?g;&*E0H}`8- znANV}jY@T3=*A@7sww*P<5=X3CFBB<-JBcY+AVaTMOj$kSfq!^Tj;q`iKKQybKY#b z*b!(aQ*ob2;&BoevKW$`?gLurfJAakw80~CI&~sxIp<8=3^hH`f2?Ttt+@gsyM{V^ zk8@16mkvjHU37u!S~BAri-%%0HdhzATsJdbR0*zpXUDW7y1W{XK~8paz8LhO@iV)N zO54cdWq||1N({Q#sy52nNa9a+UlFw5fh;#1T{)8P8OX9ObnXLP&+W7MewBB&H&sW{ zD0t;*eACTzCaR-G7&=CFtAx2uxb*5MBVuWVybjq|3vUydAC{cYyy&~Q^ji{1OC%Ou zIXv4Y_H0&u6pCiw@Z68bznpV*gyF-w5ScMg;G?pmUOE)Wonc40a#UrFl{E9Cr|QCu zxhLcV0@bSMN+O!(e5?L6p683pua}BU9n180xtS|g>Ar*VSb?`Q)aO-RM7D1d&)3%Y zKiT`W^vvEl$u7u!n%bbIP-CN7@l!4D?&hpCM&o9z=!h^eXew-o=xSY!?`cI%DfjrG zsiko;T~bd`nceU`s@qs!qF3Pql~P^7HB)WT6jocO$(B}D9=tnzt?S;Lja6xtf*oHw zS>sll<}0zHG>U_5iWO7MvXklz$!zZ`SvyeA2g0huTB~iV8B47pWR}P}lWG{dGO!iT zX^;hx?i=weh^m+89kGw_CDh~az3&H_@4z!z5D>}JnpYyCzlh>i?68!B228xrMzerD zD=?g4J*dXOUNhcPQ%FA#(w`0$V}~_N(HGjxl}x13}>4+m1vKT`VT~L*2!MtUa7nahp=E`dd{wC0P3fksXO7XHqWS?#cToPprAdc|$4lb6;Hu-Z7yQ3vGXuLuW&K#QYnBPs#h=8p883vx|-G$FnA)&-cf-nK$J? zt#EX!aPO{VtW2|o@zv26jn7z3S0|G3d$EPEt;{aUzsEA`tNAUy8y1X9w|yhgD)vkk8v%V^5Z@D{Z6dP{1a})8w6lW*%#w*fqr0)*^e+ zY$&qWzHbL#4IA6+K{1a`L}J$-O}%a%(H+lnE%LoFzyeT8MTX1UJ46=i8*|8c6OU1i z!CRi~8(+{0`u%KCJsi!3Jt<8F+A}DI4tyYGRZ1ME^tu?axt`rEV^;Z`fjh09not8*i zFOBz!z7gGKai{hdoQig7mVR2b2Ka>CN$lF*eXQ_zJ^HRI<5QdWgMzVLCFFWz@TK5K zL0o&G$N#eD?^DzrBMs=UMP94@hi`0cD$NtzAh-hd9TAj?OK*}GyZQv>=P`0}hn^4@ zzn=&^XUsBdV$0C@&&D|aiCWr3lCB7}`ZL*=_B=OAq|z5&(W+{(`Q>B}IwkDRfm5}0 zE)#wN>)5I7@`-$rT_^E(@K0b7|(ZS3Do{{u4b{7~ZE=7Jr&3+PsPxOf<#VeRNpq zduqsJ11n1{X65myf##;x#%kfPNiA*Z9vVVc3S|R@_!x5|sPJZcy61t0TY*D#lhvF( zCB!jw zU^=~n+E1bgJNj-PhmJlQG)=^17ZQLg$Zd-mR}QnPYE-1BmSCf4mfmUu#$r}_3pgtP zt~V4&6&t7bl1b9&$eAgsK74mb4Tgb4`RZJFYJ|m{sG?^BsVtfva&gSk$DlqNahMBz zq>EWO-lfVSa|Jpya^WH$s=!JhTOf9_WRv-x+9GO(|0MW@yaR^ayQ}_BG0k_KL+dkH zyPhq5p${HsN9PilI(fLTK7UGLX!uja>5!533_q&b(CA1v-m%^okX^^xqte@I`f^P1 zj%2mBz%B3fjzC8&|~CI70~-7OJb@0IhmZ&<0lPp#hQ_Sx;xJ4RMs zCPz_zXB6wBAtX-w_}Hua?>+GKtw*AF%yY&X)XTkiF1r6e3?Fj-4E;x=sn{n{i)fS! zI~zMzJ99{+H=N=^lqgkQ_+-zWdrlUPX1|yLFUnW?rY=8%xSqIiYum*mj|7}9_(0b! z>nuf)70^@4dt=gIdihKAXVYhIEMC=_NYWodXBx7G&dvsjraYR_szx-yd6~XE7W~=B zUW;+CUiof&SBk~$ci+R#BqlOX>KHyC|N9;>26@-H_1FnWm7A8|`AS zc0l!NZ?wC<=c8744tLNw#=EG1#!Px^pb~5ixS%n>s%*dGSdnwRiPK>x6N@&M-Si!O z+99S^BvFo!rjA8t%IK=AcjD=}V|aO-{8oM@2Rk|{6=OFS&`jD-L)=<>WZ3J`!tt!> zk+C!f+>sjZOwEZ-imPRjxmboCjo)8sl}+Cdq1w#UBv6M1uIlq-z`;a3Hp;h>#SyPl zJA1VHaOr_ZMwN<{Gr4PD`q(u6X-5l0>F5*!0-U2p{Dbpt3%l=&&IYap^KuH}JvH{c z6=pUgGpfSXm#gj%l%tl5i;oNaqXmPH;q2%7s05^%fVaX9Zb9GZdHQs_Fg6ijJW^sP z)b>b?ThuGLZ5zGh8a0mNl?(yahvp~T74ex>(YH9e^YAeALBCe{Zl~{NV>NDX7yVq+ zTbewd*^$QH;a&TUcD2`r7rkQz@djJvH}BW%mDRFJdJ^*kAIuTSZ;zsquVK6zE% z(qQ)wR*35It_kW};kC<)|K+Zug;T+@6x0NtKn15h@zc@cS$)rmVgP?_MZJY-Xo%Gt&CgFkK&fqVwPfs z3a3&-s~rqj*;w!T7uG7+zQ~_>4hKt>cni5DXbP{%J%2;8FY?xJ!E0S}q)NrL;C=7h?3242!q-LjaMb+%Vpj{vGvV+u`2Iqi&h4f=rJ#ciN^fY&nJ^Z z?qDGDEZk}^B4DNhM9)8Sci_v3c5M%md9aZ;>1J99d^gA&Pz~(l6o0`F8LT*#sh7E7 zC9;$^rT`&@Mnm{)`W-8e+&#PVr9Bg(^Tn>};e3nu9>{-`Qv*@ICaL4*-M{$tW?xjT zn9m(k7$bh6_JHxl>^*Y@PvtVozTppv!b~p(>7x^ zpY%`zZPUHU8+PtXzc8q8U*heZoQGVW2UmXTTV>Iv*E>GEg&ku{T-u9WtMxXPI;LNf z>9FUNgoz?@ur4MQ><;L$9ynchh;>=ppF7qqH8feI`dd5i3V5gRNy)e@*$wv-10?qR zCFxJ#O?%e{hYo$?6GL0xk*}ZNKE>{D))mr63&ZJGQ*PF!vKE3!a!Ke8y96KaY&=H1 zCF3>P+?b7_*7lpon7PyfR-qL23ECbkr8`qtso=69TzVjocN9tPW*c#e;=tm-a+U6% z3@;F=3*Awp5tC>mWO^cr$I}{hqhpaT-j08QhUG~(^LX~fnG|{{YB_W|sf} diff --git a/docs/api-doc-update-spec.example.json b/docs/api-doc-update-spec.example.json new file mode 100644 index 0000000..2477ca5 --- /dev/null +++ b/docs/api-doc-update-spec.example.json @@ -0,0 +1,56 @@ +{ + "docName": "", + "docMeta": { + "updatedAt": "", + "version": "" + }, + "group": { + "groupName": "<分组名称>", + "module": "" + }, + "methods": [ + { + "method": "", + "description": "<接口说明>", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [ + { + "name": "", + "type": "string", + "required": true, + "source": "body", + "description": "<参数说明>" + } + ], + "response": [ + { + "name": "", + "type": "string", + "required": true, + "description": "<返回字段说明>" + } + ], + "errors": [ + { + "code": 400, + "message": "<错误说明>" + } + ] + } + ], + "change": { + "version": "", + "date": "", + "summary": "<本次变更摘要>", + "methods": [ + "" + ], + "notes": [ + "<变更说明 1>", + "<变更说明 2>" + ], + "type": "updated" + } +} \ No newline at end of file diff --git a/docs/api-doc-update-workflow.md b/docs/api-doc-update-workflow.md new file mode 100644 index 0000000..eccf22b --- /dev/null +++ b/docs/api-doc-update-workflow.md @@ -0,0 +1,103 @@ +# API 文档 JSON 固定写入流程 + +## 现有 JSON 结构 + +仓库内现有 API 文档分两类: + +1. `methods/.json` + - 根节点是对象 + - 关键字段固定为 `module`、`description`、`version`、`updatedAt`、`headers`、`methods.groups` + - `methods.groups` 为数组,每个 group 固定为 `groupName`、`module`、`list` + - `list` 中每个 method 固定包含 `method`、`description`、`isNeedAuth`、`isNeedLogin`、`headers`、`params`、`response`、`errors` + +2. `methods/changes/.json` + - 根节点是数组 + - 每条变更记录建议固定包含 `version`、`date`、`summary`、`methods`、`notes` + - 可选补充 `type` + +## 固定输入 spec + +后续 API 文档写入统一通过脚本读取一个 spec JSON 完成,spec 结构固定如下: + +```json +{ + "docName": "system", + "docMeta": { + "updatedAt": "2026-04-15", + "version": "0.3.5" + }, + "group": { + "groupName": "基础模块", + "module": "index" + }, + "methods": [ + { + "method": "index.example", + "description": "接口说明", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [], + "params": [], + "response": [], + "errors": [] + } + ], + "change": { + "version": "2026.04.15-system-06", + "date": "2026-04-15", + "summary": "一句话说明本次接口文档变更", + "methods": [ + "index.example" + ], + "notes": [ + "补充关键字段说明。" + ], + "type": "updated" + } +} +``` + +说明: + +- `docName` 目前必须对应已存在的 `methods/system.json`、`methods/qimen.json`、`methods/gateway.json` +- `group` 用于定位或创建目标分组 +- `methods` 为要写入的完整 method 文档对象数组,脚本按 `method` 字段 upsert +- `change` 默认必填;仅当明确是纯格式修复且不需要追加历史时,才允许加 `--doc-only` + +## 固定命令 + +先做 dry-run: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run +``` + +确认无误后执行写入: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json +``` + +纯文档主文件修补且不追加 changes 时: + +```powershell +npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only +``` + +## 脚本保证 + +`script/update-api-doc.cjs` 会执行以下动作: + +- 校验 spec JSON 是否符合固定结构 +- 校验目标 `methods/*.json` 与 `methods/changes/*.json` 是否可解析 +- 按 group + method 做 upsert,避免手写 JSON 时把括号、逗号、层级写坏 +- 检查 change version 是否重复 +- 保留目标 JSON 原有缩进与换行风格 + +## 推荐流程 + +1. 先核对代码与测试,确认真实接口契约 +2. 如果是 system 参数结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs` +3. 按 [docs/api-doc-update-spec.example.json](docs/api-doc-update-spec.example.json) 复制一份 spec 到 `temp/` +4. 先执行 dry-run,再执行正式写入 +5. 最后补充必要的 `docs/*.md` 或 `README.md` \ No newline at end of file diff --git a/docs/notification-event-api.md b/docs/notification-event-api.md index 0e9baed..dee3609 100644 --- a/docs/notification-event-api.md +++ b/docs/notification-event-api.md @@ -14,6 +14,7 @@ 当前已落地事件: - `receiving_completed`:收货完成通知 +- `order_cancel_intercepted`:订单取消失败并触发拦截执行通知 - `store_warehouse_print_quantity_adjusted`:货主面单余额人工调整通知 --- @@ -51,9 +52,10 @@ await ctx.service.systems.notice.send({ | event | 含义 | |---|---| | `receiving_completed` | 收货单完成通知 | +| `order_cancel_intercepted` | 订单取消失败并触发拦截执行通知 | | `store_warehouse_print_quantity_adjusted` | 货主面单余额人工调整通知 | -> 当前正式注册的业务事件包括 `receiving_completed`、`store_warehouse_print_quantity_adjusted`。 +> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`、`store_warehouse_print_quantity_adjusted`。 对于外部订阅方来说,判断消息类型时,优先看: @@ -136,7 +138,9 @@ Content-Type: application/json "name": "广州仓", "code": "", "config": { - "max_notice_webhook_count": 5 + "max_notice_webhook_count": 5, + "default_express_code": "STO", + "default_platform_code": "TB" } }, "store": { @@ -240,6 +244,7 @@ Content-Type: application/json 下一步可继续补充: - `receiving_cancelled` +- `order_cancelled` - `stock_low` - `stock_changed` - `entry_order_created` diff --git a/docs/notification-webhook-capability.md b/docs/notification-webhook-capability.md index c115cab..3b235f3 100644 --- a/docs/notification-webhook-capability.md +++ b/docs/notification-webhook-capability.md @@ -60,6 +60,8 @@ await ctx.service.systems.notice.send(options) | 字段 | 说明 | |---|---| | `max_notice_webhook_count` | 当前主体最多允许绑定 / 触达的消息推送接口数量,默认 `5` | +| `default_express_code` | 默认快递编码,默认 `STO` | +| `default_platform_code` | 默认平台编码,默认 `TB` | --- @@ -83,8 +85,9 @@ await ctx.service.systems.notice.send(options) | event | 说明 | |---|---| | `receiving_completed` | 收货单完成通知 | +| `order_cancel_intercepted` | 订单取消失败并触发拦截执行的通知 | -> 当前正式注册的业务事件仅保留 `receiving_completed`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。 +> 当前正式注册的业务事件包括 `receiving_completed`、`order_cancel_intercepted`;`all` / `*` 作为通配订阅值继续保留。收货完成事件的独立 API 文档见:`docs/notification-event-api.md`。 --- @@ -139,7 +142,9 @@ await ctx.service.systems.notice.send(options) "name": "广州仓", "code": "", "config": { - "max_notice_webhook_count": 5 + "max_notice_webhook_count": 5, + "default_express_code": "STO", + "default_platform_code": "TB" } }, "store": { @@ -178,9 +183,12 @@ await ctx.service.systems.notice.send(options) | `all` | 接收全部已注册通知 | | `*` | 兼容旧配置,等价于 `all` | | `receiving_completed` | 只接收收货完成事件 | +| `order_cancel_intercepted` | 只接收订单取消拦截事件 | > 若需新增其他事件,必须先在 `app/model/notification_webhook.js` 完成注册,否则发送入口会直接拒绝。 +当前订单取消拦截通知由 `app/service/qimenMethods/order.js` 在拣货状态或打印状态未结束时发送,事件码为 `order_cancel_intercepted`。 + --- ## 8. 命中与分发规则 diff --git a/docs/order-workbench-list-api.md b/docs/order-workbench-list-api.md new file mode 100644 index 0000000..1c055d5 --- /dev/null +++ b/docs/order-workbench-list-api.md @@ -0,0 +1,186 @@ +# 订单工作台 List 接口说明 + +本文档说明订单工作台(Order Workbench)中可用的 list 接口、参数约定、返回结构与行为要点。 + +**变更记录** +- 本次已在 methods/system.json 中补充以下 method 定义,并在 methods/changes/system.json 中追加变更记录(参见变更文件),用于对外说明新增的 list 接口与分页/where 支持。 + +**新增/确认的接口(method 名称,主入口)** +- order.list —— 订单工作台总列表入口(汇总所有分组) +- order.reviewOrder.list —— 待审核订单工作台(step=0) +- order.pendingOrder.list —— 待处理订单工作台(step in [1,2]) +- order.expectionOrder.list —— 待处理异常订单工作台(step=3) +- order.entrustOrder.list —— 委托外仓订单工作台(outsourced 模型) +- order.deliveryOrder.list —— 配送订单工作台(dispatch 模型,dispatch_lane=m4) +- order.deliveryExpectionOrder.list —— 配送异常订单工作台(dispatch 模型,dispatch_lane=m5) +- order.archiveOrder.list —— 归档订单工作台(history 模型) + +兼容说明:代码中存在若干旧兼容入口(例如 getreviewOrderlist、getdeliveryOrderlist、getpendingOrderlist、getexpectionOrderlist、getentrustOrderlist、getarchiveOrderlist 等),这些为兼容旧调用保留的旧名入口,不作为首选主入口;建议新调用使用上文列出的主入口。 + +**工作台语义(简要)** +- order.list:总列表入口,返回跨分组的订单集合,适用于需要不分组的通用搜索/分页场景。 +- reviewOrder:待审核(审核步骤为未审核)工作台,用于审核操作筛选与展示(默认 step=0)。审核提交接口仅接收 ids,批量审核,严格同仓校验,不做兼容。 +- pendingOrder:待处理工作台,通常包含需要人工或系统继续处理的订单(默认 step in [1,2])。 +- expectionOrder:异常工单集合(默认 step=3),用于定位异常状态订单。 +- entrustOrder:委托外仓相关订单,使用 outsourced 模型。 +- deliveryOrder / deliveryExpectionOrder:配送相关工作台,使用 dispatch 模型,分别以 dispatch_lane=m4 / m5 筛选。 +- archiveOrder:归档历史订单,使用 history 模型。 + +实现要点(参考实现位于 app/service/systemMethods/order/*): +- 模块实现会根据模块名选择不同物理模型(current / dispatch / outsourced / history),由 OrderBaseService#getOrderModel 决定。 +- 每个模块还定义了 `defaultWhere`(例如 reviewOrder 的 step=0 等),请求的 `where` 会与模块默认条件合并后一起用于构造最终查询。 + +参数说明(公共约定) +- pagination: object + - pagination.page: number(可选),页码,从 1 开始,默认 1。 + - pagination.pageSize: number(可选),每页条数,默认 20。注意:服务端对 pageSize 做上限截断,最大不可超过 200(见下)。 +- where: object(可选) + - 统一的筛选条件对象;支持两种写法: + - 标准化结构:{ field: { operator: 'eq'|'in'|'like'|..., value: ..., type?: 'string'|'number' } } + - 简写:{ field: value }(会被自动转换为 { operator: 'eq', value } 或在传数组时转换为 in) + - 服务端会先对 where 做 normalize(兼容简写与 values 字段),再走 parseWhereConditions 生成底层查询条件,最后与模块的 defaultWhere 合并(后者优先级低于请求入参)。 + - 常见可用字段:id、delivery_order_code、order_status、dispatch_lane、quickWhere 等(具体过滤字段以实现解析器支持为准)。 +- sort: object(可选) + - 支持 sortField / sortOrder 或 field / order;实现层会映射到允许的字段集合(如 id、step、status、delivery_time、updated_at 等),默认按 updated_at DESC, id DESC。 + +分页/大小限制 +- 默认 pageSize=20。 +- 最大 pageSize: 200(服务端在 normalizePagination 中对 pageSize 做截断,防止单次请求返回过大数据)。调用方仍应合理控制 pageSize,避免前端一次性请求过多数据。 + +返回结构(公共约定) +- list: array — 当前页的记录数组(每项为订单对象的序列化行,字段视具体模型与序列化而定)。 +- pagination: object + - pagination.page: number — 当前页 + - pagination.pageSize: number — 每页条数(实际返回值为服务端截断后的值) + - pagination.total: number — 符合条件的总记录数 + - pagination.totalPages: number + - pagination.hasPrevious / hasNext: boolean + +订单列表 raw 字段字典(通用) +- 说明:以下字段为所有订单列表的 raw 基础字段;`order.deliveryOrder.list` 和 `order.deliveryExpectionOrder.list` 额外包含 `dispatch_lane`;服务层还会补充 `express_numbers` 与 `waybill_codes` 两个派生字段,二者内容一致,都是该订单绑定的多个快递号。 + +| 字段 | 类型 | 中文语义 | 枚举/说明 | +| --- | --- | --- | --- | +| id | number | 订单主键 ID | 订单记录主键 | +| delivery_order_code | string | 发货单号 | 订单单号 | +| pre_delivery_order_code | string | 预发货单号 | 预发货阶段单号 | +| pre_delivery_order_id | string | 预发货单ID | 预发货记录关联 ID | +| order_type | string | 订单类型 | 业务类型标识 | +| warehouse_code | string | 仓库编码 | 仓库基础编码 | +| order_flag | string | 订单标记 | 订单标签/标记信息 | +| source_platform_code | string | 来源平台编码 | 原始平台编码 | +| source_platform_name | string | 来源平台名称 | 原始平台名称 | +| sys_platform_code | string | 系统平台编码 | 系统内平台编码 | +| sys_platform_name | string | 系统平台名称 | 系统内平台名称 | +| create_at | string | 创建时间 | ISO 时间字符串 | +| delete_at | string | 删除时间 | ISO 时间字符串,通常为空 | +| updated_at | string | 更新时间 | ISO 时间字符串 | +| place_order_time | string | 店铺创建订单时间 | 平台下单时间 | +| pay_time | string | 支付时间 | 支付完成时间 | +| pay_no | string | 支付单号 | 支付流水号 | +| service_code | string | 集包服务编码 | 集包/服务编码 | +| operator_name | string | ERP审核人 | 审核人姓名 | +| operate_time | string | ERP审核时间 | 审核时间 | +| delivery_time | string | 发货时间 | 发货完成时间 | +| shop_nick | string | 店铺名称 | 店铺昵称 | +| seller_nick | string | 卖家名称 | 卖家昵称 | +| buyer_nick | string | 买家名称 | 买家昵称 | +| total_amount | number | 订单总金额 | 金额字段,保留两位小数 | +| item_amount | number | 商品总金额 | 金额字段,保留两位小数 | +| discount_amount | number | 订单折扣金额 | 金额字段,保留两位小数 | +| freight | number | 快递费用 | 金额字段,保留两位小数 | +| ar_amount | number | 应收金额 | 金额字段,保留两位小数 | +| got_amount | number | 已收金额 | 金额字段,保留两位小数 | +| service_fee | number | COD服务费 | 金额字段,保留两位小数 | +| logistics_code | string | 物流公司编码 | 物流公司编码 | +| logistics_name | string | 物流公司名称 | 物流公司名称 | +| sys_logistics_code | string | 系统物流公司编码 | 系统内物流编码 | +| sys_logistics_name | string | 系统物流公司名称 | 系统内物流名称 | +| express_code | string | 面单号前置 | 面单号前缀 | +| logistics_area_code | string | 快递区域编码 | 大头笔/区域编码 | +| delivery_type | string | 发货服务类型 | 发货方式 | +| is_urgency | enum | 是否紧急 | Y=是,N=否 | +| invoice_flag | enum | 是否需要发票 | Y=需要,N=不需要 | +| status | enum | 订单状态 | pedding=待处理,created=已创建,cancel=已取消,error=异常 | +| name | string | 收件人姓名 | 收件人 | +| zip_code | string | 收件人邮编 | 邮编 | +| tel | string | 收件人电话 | 电话号码 | +| mobile | string | 收件人移动电话 | 手机号 | +| email | string | 收件人邮箱 | 邮箱 | +| country_code | string | 国家编码 | 国家/地区编码 | +| province | string | 省份 | 收件地址省 | +| city | string | 城市 | 收件地址市 | +| area | string | 区 | 收件地址区 | +| town | string | 镇 | 收件地址镇 | +| detail_address | string | 详细地址 | 街道/门牌详情 | +| id_type | string | 证件类型 | 证件类型 | +| id_number | number | 证件号码 | 证件号 | +| oaid | string | OAID | 设备/终端标识 | +| sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 | +| store_id | number | 货主ID | 货主主键 | +| warehouse_id | number | 仓库ID | 仓库主键 | +| from_key | number | 来源键 | 来源系统键值 | +| items | string | 商品JSON字符串 | 原始商品明细 JSON | +| items_count | number | 商品种类数 | SKU 种类数 | +| items_total | number | 商品总数 | 商品件数总和 | +| items_weight | number | 总重量(kg) | 总重量 | +| items_hash | string | MD5哈希值(32位) | 商品明细哈希 | +| items_crc | number | CRC32校验码 | 商品明细校验码 | +| wave_id | number | 波次ID | 0 表示未分配 | +| post_status | enum | 分配快递号状态机 | padding=处理中,fin=完成,timeout=超时,error=失败,none=未开始 | +| storage_status | enum | 分配储位状态机 | padding=处理中,fin=完成,error=失败,none=未开始 | +| pick_status | enum | 拣货状态机 | padding=处理中,fin=完成,error=失败,none=未开始 | +| pack_status | enum | 打包状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | +| inspection_status | enum | 检验状态机 | none=未开始,padding=处理中,running=进行中,fin=完成,error=失败 | +| step | number | 订单步骤 | 0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭 | +| print_status | enum | 打印状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | +| claim_status | enum | 领取状态机 | none=未开始,padding=处理中,fin=完成,error=失败 | +| outbound_status | enum | 出库状态机 | none=未开始,padding=处理中,fin=完成,timeout=超时,error=失败 | +| lock_status | enum | 锁定状态机 | none=未锁定,warehouse=仓库锁定,store=货主锁定 | +| intercept_status | enum | 拦截状态机 | none=未拦截,requesting=请求中,requested=已请求,intercepting=拦截中,intercepted_in_transit=运输中拦截成功,intercepted_at_warehouse=仓库拦截成功,returning=退回中,returned=已退回,delivered_by_mistake=误签收,timeout=超时,cancelled=已取消,failed=失败,exception=异常 | +| dispatch_lane | string | 配送通道/分区 | 仅配送相关列表可能出现,常用于区分 m4 / m5 等通道 | +| express_numbers | array[string] | 快递号列表 | 服务层聚合字段,内容来自 wms_order_express.waybill_code | +| waybill_codes | array[string] | 运单号列表 | 与 express_numbers 内容一致,为兼容前端使用保留 | + +补充说明 +- `express_numbers` 和 `waybill_codes` 都来自订单绑定的多条快递记录,适合前端直接渲染“多个快递号”。 +- `sys_platform_name`、`sys_logistics_name` 已由服务层归一化输出,前端无需再回表查询。 +- `dispatch_lane` 仅在 `order.deliveryOrder.list` / `order.deliveryExpectionOrder.list` 这两个配送类列表中出现;其余列表通常不返回该字段。 + +其他注意事项 +- `where` 的解析与支持的特殊字段由 parseWhereConditions 决定;若需要支持新的复杂筛选(如跨表/聚合条件),请先在解析器和后端模型中确认可支持的 specialFieldMap 与解析策略。 +- 推荐使用标准化 where 结构({ operator, value })以避免歧义;历史简写会被自动规范化,但可读性较差。 +- 兼容入口(get*)保留以兼容历史客户端,但文档与新开发均建议使用上述主入口方法名;兼容入口可能在不同 module 下存在重复实现(index + 子模块),以兼容不同调用路径。 + +方法清单(已在 methods/system.json 中登记) +- order.list +- order.reviewOrder.list +- order.pendingOrder.list +- order.expectionOrder.list +- order.entrustOrder.list +- order.deliveryOrder.list +- order.deliveryExpectionOrder.list +- order.archiveOrder.list + +是否需要补充其它文档同步? +- 建议同步更新: + - 若有门户/前端 API 文档站(自动生成或展示 methods/system.json 的地方),应部署或刷新以展现新增条目。 + - 若存在 SDK 或对接说明(如 qimen 或第三方对接文档),如使用到工作台 list 场景也建议补充示例请求与常用 where 范例。 + +示例请求(简要) + +请求体示例: +{ + "pagination": { "page": 1, "pageSize": 50 }, + "where": { "delivery_order_code": { "operator": "like", "value": "ABC" }, "create_time_start": { "value": "2026-04-01" } }, + "sort": { "sortField": "updated_at", "sortOrder": "DESC" } +} + +响应示例(简要): +{ + "list": [ /* 订单对象数组 */ ], + "pagination": { "page":1, "pageSize":50, "total":1234, "totalPages":25, "hasPrevious":false, "hasNext":true } +} + +-- +文档维护者:WMS 文档代理 diff --git a/docs/stock-expiry-module.md b/docs/stock-expiry-module.md new file mode 100644 index 0000000..4c17bce --- /dev/null +++ b/docs/stock-expiry-module.md @@ -0,0 +1,80 @@ +# 库存效期模块(定时预警任务) + +本文档基于源码实现(单一事实来源),定位与说明项目中关于库存效期扫描与预警的定时任务行为。实现文件:app/schedule/notice_stock_remaining.js。 + +## 概要 + +- 任务名称/文件:`app/schedule/notice_stock_remaining.js` +- 调度配置:`interval: '30s'`、`type: 'worker'`、`immediate: false`(见文件头部 schedule 配置) +- 目的:扫描启用保质期管理的仓库商品与对应库存(wms_stock_warehouse / wms_storage),对即将到期的库存发送效期预警通知,并通过缓存进行去重。 + +## 主要实现要点(按代码实现逐项说明) + +1. 并发保护 + - 使用进程级标记 `ctx.app._noticeStockRemainingRunning`,若上一轮尚未结束则跳过本次运行。 + +2. 通知去重缓存 + - 缓存键:`notice_stock_remaining_notified_list`(文件常量 `CACHE_KEY`)。 + - 缓存 TTL:24 小时(`CACHE_TTL_SECONDS = 24 * 60 * 60`)。 + - 缓存存储格式兼容数组或对象,读取后标准化为 `storage:{id}` 格式的键集合用于去重。 + +3. 读取候选商品(wms_stock_warehouse) + - 查询条件(stockWhere): + - `is_shelf_life_mgmt: 'Y'` + - `remaining_threshold_days: { [Op.gt]: 0 }`(使用 `Sequelize.Op.gt`) + - 查询字段:`id, item_code, item_name, store_id, warehouse_id, remaining_threshold_days` + - 排序:`remaining_threshold_days ASC, id ASC` + - 结果用于构建 `stockMap`(包含每个 stock 的阈值),并计算 `maxThresholdDays`(用于缩小后续库存扫描时间窗口)。 + +4. 计算候选库存时间窗口 + - 以当前时间 `now`,计算 `maxExpiryDate = new Date(now.getTime() + maxThresholdDays * DAY_MS)`,其中 `DAY_MS = 24 * 60 * 60 * 1000`。 + +5. 查询候选库存记录(wms_storage) + - 查询条件(storageWhere): + - `stock_id` 在上一步筛选得到的 `stockIds` 列表中 + - `is_enabled: 1` + - `delete_at: null`(paranoid 软删除过滤) + - `quantity: { [Op.gt]: 0 }` + - `expiry_date: { [Op.ne]: null, [Op.lte]: maxExpiryDate }`(到期日非空且小于等于计算窗口) + - include:关联 `LocationSpace`(别名 `space`),属性取 `space_code, custom_name`,`required: false`。 + - 排序:`expiry_date ASC, inbound_time ASC, id ASC`。 + - 注意:实现中调用的是 `findAll`(无分页),因此会拉取匹配的全部候选记录并在内存中逐条处理。 + +6. 单条记录处理与判断逻辑 + - 对每条 `storageRecord`: + - 生成去重键 `notifyKey = storage:{storageId}`(若无法解析 id 则跳过)。 + - 若该 `notifyKey` 已存在于缓存集合则跳过(避免重复通知)。 + - 根据 `stockMap` 获取本条记录对应商品的 `thresholdDays`(阈值天数);若不存在或阈值 <= 0 则跳过。 + - 读取 `expiry_date`,将其解析为 Date;若无或解析失败则跳过并记录 warn。 + - 计算剩余天数:`remainingDays = Math.max(0, Math.ceil((expiryDate - now) / DAY_MS))`。 + - 若 `remainingDays > thresholdDays` 则跳过(未达到阈值);否则组装通知并发送。 + +7. 通知发送与元数据 + - 使用通知服务:`ctx.service.systems.notice.send(payload)`。代码中若 `noticeResult.success === false` 则认为发送失败并保留重试;异常时记录错误并继续处理下一条。 + - 通知 payload 包含(示例字段): + - `warehouseId`, `storeId`, `subject`(id/type/name), `businessName: 'storage'`, `event`(常量 `storage_transfer_completed`),`title`, `content`, `businessId: storageId`, `messageType: 'text'` + - `metadata`:包含 `cacheKey`, `storageId`, `stockId`, `notifyKey`, `thresholdDays`, `remainingDays`, `warehouseId`, `storeId`, `stock: { id, item_code, item_name }`, `storage: { id, batch_no, expiry_date (ISO) }` + +8. 回写去重缓存 + - 成功发送后,将 `notifyKey` 添加到 `updatedNotifiedList` 并在本轮结束后使用 `ctx.app.setCacheAsync(CACHE_KEY, dedupedList, CACHE_TTL_SECONDS)` 回写缓存(如果 `setCacheAsync` 可用)。 + +9. 日志与统计 + - 任务会记录候选商品数、候选库存数、实际发送计数与跳过计数;发送失败与异常会记录 warn/error 日志。 + +## 与公开 API 的关系 + +- 任务为内部定时任务(非 system API),其查询条件与模型字段直接对应数据库表 `wms_stock_warehouse` 与 `wms_storage`。 +- 若需要通过 API 查询某个商品的库存明细(包含批次与过期信息),请使用已有的 system 方法 `stock.warehouse.getStockDetail`(该接口支持 `pagination` 与 `group_by_batch`,API 文档位于 `methods/system.json`),与本任务的扫描逻辑互为补充:任务用于主动推送预警,API 用于按需查询。 + +## 注意事项(运维/集成) + +- 通知发送依赖 `ctx.service.systems.notice`,在无该服务或返回异常时任务仅记录日志。 +- 任务扫描不分页:对于极大库存量的仓库,建议评估 `maxThresholdDays` 与索引(`idx_expiry_date` 已存在于模型)对查询性能的影响,或考虑将查询改为分片/分页处理。 +- 去重缓存使用全局缓存接口 `getCacheAsync` / `setCacheAsync`,请保证缓存后台(如 Redis)可用以避免重复通知泛滥。 + +## 实现位置(代码参考) + +- 定时任务文件:app/schedule/notice_stock_remaining.js +- 依赖模型:app/model/stock_warehouse.js、app/model/storage.js、app/model/location_space.js +- 依赖服务:ctx.service.systems.notice + diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md index 99208f1..eab9ee7 100644 --- a/docs/storage-receiving-api.md +++ b/docs/storage-receiving-api.md @@ -217,3 +217,111 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr - 自动刷新收货单统计数据 适合作为收货单明细与系统商品标准匹配接口对外说明使用。 + +--- + +## 11. 接口:storage.receiving.detailChange + +### 11.1 接口用途 + +用于修改收货单明细(明细行)中的数量、箱规、批次与商品信息,并触发收货单统计与相关联动(例如库存/统计刷新与操作日志)。典型场景为:前端在录入收货明细后,补录实际收货数量、箱数、托盘数、批次/生产/到期信息或回写条码与商品名称等。 + +> 注意:方法在 system 层以 `POST /system?method=storage.receiving.detailChange` 调用,需包含 `Authorization: Bearer `,仓库上下文来源于 `ctx.user.store_id`。 + +### 11.2 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|---|---:|---:|---| +| `id` | `number` | 是 | 收货明细 ID(必填) | +| `receiving_id` | `number` | 是 | 收货单 ID(必填) | +| `actual_quantity` | `number` | 否 | 实际收货数量 | +| `batch_number` | `string` | 否 | 批次号 | +| `production_date` | `string` | 否 | 生产日期(ISO 或可解析的日期字符串) | +| `expiry_date` | `string` | 否 | 到期日期(ISO 或可解析的日期字符串)。若传入的 `expiry_date` 小于当前日期,接口会拒绝并返回 400(见错误码) | +| `box_quantity` | `number` | 否 | 箱数 | +| `boxes_per_pallet` | `number` | 否 | 每托盘箱数 | +| `pallet_quantity` | `number` | 否 | 托盘数 | +| `space_id` | `number` | 否 | 目标库位 ID(可用于回写库位) | +| `remark` | `string` | 否 | 备注 | +| `system_product_id` | `number` | 否 | 系统商品 ID(StockWarehouse.id)。若提供,系统会回填条码、重量、箱规、商品名称与快照等;若不提供,可单独更新 `barcode`/`product_name` | +| `barcode` | `string` | 否 | 条码(当未传 `system_product_id` 时,可单独更新) | +| `product_name` | `string` | 否 | 商品名称(当未传 `system_product_id` 时,可单独更新) | +| `box_width` | `number` | 否 | 箱宽(单位按系统约定) | +| `box_height` | `number` | 否 | 箱高 | +| `box_length` | `number` | 否 | 箱长 | +| `weight` | `number` | 否 | 毛重/重量 | + +> 说明:`id` 与 `receiving_id` 为必须校验项,其他字段为可选—仅在传入时会写入/覆盖对应明细字段。传入 `system_product_id` 时,系统优先使用系统商品信息回填字段(前端可只传 `system_product_id` 来自动回填)。 + +### 11.3 请求示例 + +```json +{ + "id": 501, + "receiving_id": 123, + "actual_quantity": 10, + "batch_number": "B20260401", + "production_date": "2026-04-01", + "expiry_date": "2027-04-01", + "box_quantity": 2, + "boxes_per_pallet": 10, + "pallet_quantity": 0, + "space_id": 1001, + "remark": "样例备注", + "system_product_id": 8888 +} +``` + +### 11.4 返回结构(成功) + +成功时返回 `code: 200`,`message` 为 `修改成功`,`data` 中包含基础标识与关键展示字段: + +```json +{ + "code": 200, + "message": "修改成功", + "data": { + "id": 501, + "receiving_id": 123, + "actual_quantity": 1, + "product_name": "测试商品", + "barcode": "", + "system_product_id": null, + "updated_at": "2026-04-01T00:00:00.000Z" + } +} +``` + +返回字段说明: + +- `data.id`:收货明细 ID +- `data.receiving_id`:收货单 ID +- `data.actual_quantity`:明细当前的实际收货数量(根据实现,此处返回服务端查询到的明细值) +- `data.product_name`:商品名称(若 `system_product_id` 回填则为系统商品名称) +- `data.barcode`:条码 +- `data.system_product_id`:回填或当前关联的系统商品 ID +- `data.updated_at`:明细记录的更新时间 + +### 11.5 常见错误码 + +| code | message 示例 | 含义 | +|---:|---|---| +| `400` | `收货明细ID不能为空` | 未传 `id` | +| `400` | `收货单ID不能为空` | 未传 `receiving_id` | +| `400` | `到期日期已过期,不能录入收货` | `expiry_date` 小于当前日期时返回(禁止录入已过期批次) | +| `400` | `箱数不能为负数` / `托盘数不能为负数` | 非法的箱规数值 | +| `404` | `收货明细不存在` | 明细不存在或不属于当前仓库/收货单状态不允许操作 | +| `500` | `修改失败,请稍后重试` | 服务端异常 | + +--- + +### 11.6 业务要点与实现说明 + +- 若传入 `system_product_id`,服务端尝试读取 `StockWarehouse`(同仓库)并回填:`barcode`(若前端未显式传入),`weight`,`boxes_per_pallet`、`box_height`、`box_width`、`box_length`(若启用箱规),以及 `product_snapshot` 中的货主快照信息。 +- 若未传 `system_product_id`,但传入 `barcode` 或 `product_name`,服务端仍允许更新这两个字段(并把 `system_product_id` 置为 `null`)。 +- 接口会在成功写入明细后触发收货单统计刷新(`updateReceivingStats`)并写操作日志(`RECEIVING_UPDATE_DETAIL`)。 +- 系统存在一个库存效期预警定时任务,逻辑上会扫描启用保质期管理且设置了剩余天数阈值的商品,并按库存到期日筛选候选记录后进行去重通知发送;其判断条件主要依赖 `wms_stock_warehouse.is_shelf_life_mgmt = 'Y'`、`remaining_threshold_days > 0`,以及 `wms_storage.expiry_date`(小于等于当前时间加最大阈值天数)。 + +--- + + diff --git a/methods/changes/system.json b/methods/changes/system.json index f94cafc..006cb8b 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,162 @@ [ + { + "version": "2026.04.15-system-07", + "date": "2026-04-15", + "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", + "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-06", + "date": "2026-04-15", + "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", + "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", + "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-05", + "date": "2026-04-15", + "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", + "methods": [ + "index.getExpressList", + "index.getPlatformList" + ], + "notes": [ + "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", + "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", + "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", + "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", + "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", + "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-02", + "date": "2026-04-15", + "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", + "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-03", + "date": "2026-04-15", + "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", + "methods": [ + "storeWarehouse.store.savePolicyConfig", + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", + "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-04", + "date": "2026-04-15", + "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", + "methods": [ + "order.list", + "order.manualOutboundOrder", + "order.badgeCount", + "order.outboundOrder.manualOutboundOrder", + "order.reviewOrder.list", + "order.reviewOrder.reviewOrder", + "order.pendingOrder.list", + "order.pendingOrder.reverseReviewOrder", + "order.pendingOrder.markPendingOutboundOrder", + "order.pendingOrder.cancelOrder", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", + "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", + "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-01", + "date": "2026-04-15", + "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", + "methods": [ + "store.createStore", + "store.createWarehouse" + ], + "notes": [ + "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", + "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "库存列表新增货主名称字段 stock.store_name", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", + "只同步文档,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-01", + "date": "2026-04-13", + "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", + "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", + "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", + "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" + ], + "type": "updated" + }, { "version": "2026.04.07-system-01", "date": "2026-04-07", @@ -441,4 +599,56 @@ ], "type": "changed" } - ] + , + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", + "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", + "仅更新文档(methods/system.json 与变更记录),代码行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "新增 storage.expiry.list 库存有效期列表查询接口", + "methods": [ + "storage.expiry.list" + ], + "notes": [ + "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" + ], + "type": "added" + }, + { + "version": "2026.04.13-system-03", + "date": "2026-04-13", + "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", + "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "更新 index.searchSpace 文档", + "methods": [ + "index.searchSpace" + ], + "notes": [ + "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" + ], + "type": "updated" + } +] diff --git a/methods/system.json b/methods/system.json index 3b4ddbc..e595ca6 100644 --- a/methods/system.json +++ b/methods/system.json @@ -475,7 +475,7 @@ }, { "method": "index.searchSpace", - "description": "index.searchSpace 接口", + "description": "按当前仓库上下文搜索库位(使用 ctx.user.store_id;仅在 location_space 表中按 space_code/custom_barcode 搜索)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -486,8 +486,64 @@ "description": "Bearer token" } ], - "params": [], - "response": [], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,对 space_code 和 custom_barcode 做模糊匹配(%keyword%);为空时返回当前仓库下前 50 条" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "description": "全局调用结果标识,成功时为 success" + }, + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "message", + "type": "string", + "description": "返回信息" + }, + { + "name": "data", + "type": "array", + "description": "库位数组(最多 50 条),每项包含以下字段", + "children": [ + { + "name": "id", + "type": "number", + "description": "库位 ID" + }, + { + "name": "space_code", + "type": "string", + "description": "库位编码" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "库位自定义条码" + }, + { + "name": "custom_name", + "type": "string", + "description": "库位自定义名称" + } + ] + }, + { + "name": "total", + "type": "number", + "description": "本次返回的记录条数(等于 data.length,≤50)" + } + ], "errors": [] }, { @@ -500,16 +556,17 @@ { "method": "index.getExpressList", "description": "index.getExpressList 接口", - "isNeedAuth": true, + "isNeedAuth": false, + "isNeedLogin": true, + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getPlatformList", + "description": "index.getPlatformList 接口", + "isNeedAuth": false, "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], "params": [], "response": [], "errors": [] @@ -517,46 +574,12 @@ ] }, { - "groupName": "订单模块", - "module": "order", + "groupName": "订单工作台入口模块", + "module": "order.index", "list": [ - { - "method": "order.getOrderModels", - "description": "order.getOrderModels 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "order.base.getOrderModels", - "description": "订单模型能力兼容入口(当前与 order.getOrderModels 返回一致)", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, { "method": "order.list", - "description": "分页查询订单列表", + "description": "订单工作台总列表入口,查询当前登录用户仓库上下文下的订单总列表,支持 pagination / where / sort。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -573,22 +596,51 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize,兼容 currentPage / page_size / size" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、step、outbound_status、buyer_nick、mobile 与日期区间字段。示例:where.delivery_order_code={operator:like,value:SO202603}; where.status={operator:in,value:[created,pedding]}; where.step={operator:eq,value:1}。" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会自动标准化;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少仓库上下文或 where 参数格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] }, { - "method": "order.detail", - "description": "查询订单详情", + "method": "order.manualOutboundOrder", + "description": "手动触发出库迁移,将当前仓库内已出库订单同步到配送表。请求体直接透传给 orderDeliveryMigration.syncOutboundOrdersToDelivery。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -601,231 +653,601 @@ ], "params": [ { - "name": "delivery_order_code", - "type": "string", + "name": "warehouseId", + "type": "number", "required": false, "source": "body", - "description": "delivery_order_code 参数" + "description": "单仓库ID,兼容 warehouse_id" + }, + { + "name": "warehouseIds", + "type": "array", + "required": false, + "source": "body", + "description": "仓库ID 数组" + }, + { + "name": "queryTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "查询超时时间(毫秒)" + }, + { + "name": "executionTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "执行超时时间(毫秒)" + } + ], + "response": [ + { + "name": "warehouseIds", + "type": "array", + "required": true, + "description": "参与迁移的仓库ID列表" + }, + { + "name": "batchSize", + "type": "number", + "required": true, + "description": "单批处理上限,当前固定为 1000" + }, + { + "name": "outboundStatuses", + "type": "array", + "required": true, + "description": "本次迁移匹配的出库状态" + }, + { + "name": "totalSelected", + "type": "number", + "required": true, + "description": "命中的源订单数量" + }, + { + "name": "totalCreated", + "type": "number", + "required": true, + "description": "实际创建到配送表的订单数量" + }, + { + "name": "totalSkipped", + "type": "number", + "required": true, + "description": "本次跳过的源订单数量" + }, + { + "name": "totalTimeout", + "type": "number", + "required": true, + "description": "被标记为出库超时的订单数量" + }, + { + "name": "results", + "type": "array", + "required": true, + "description": "按仓库维度返回的批次结果数组,元素包含 selectedCount、createdCount、skippedCount、timeoutCount、retryableFailure 等字段" + } + ], + "errors": [ + { + "code": "400", + "description": "仓库ID为空或请求参数格式错误" + }, + { + "code": "500", + "description": "迁移失败或数据库错误" + } + ] + }, + { + "method": "order.badgeCount", + "description": "订单工作台各标签页角标计数,基于当前仓库上下文返回。配送、配送异常与归档标签固定返回 99+。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "reviewOrder", + "type": "number|string", + "required": true, + "description": "待审核角标" + }, + { + "name": "pendingOrder", + "type": "number|string", + "required": true, + "description": "待处理角标" + }, + { + "name": "outboundOrder", + "type": "number|string", + "required": true, + "description": "待出库角标" + }, + { + "name": "expectionOrder", + "type": "number|string", + "required": true, + "description": "待处理异常角标" + }, + { + "name": "entrustOrder", + "type": "number|string", + "required": true, + "description": "委托外仓角标" + }, + { + "name": "deliveryOrder", + "type": "string", + "required": true, + "description": "配送角标,固定返回 99+" + }, + { + "name": "deliveryExpectionOrder", + "type": "string", + "required": true, + "description": "配送异常角标,固定返回 99+" + }, + { + "name": "archiveOrder", + "type": "string", + "required": true, + "description": "归档角标,固定返回 99+" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少当前仓库上下文 store_id" + } + ] + } + ] + }, + { + "groupName": "订单待审核模块", + "module": "order.reviewOrder", + "list": [ + { + "method": "order.reviewOrder.list", + "description": "待审核订单列表,默认仅查询 step=0 的订单。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.reviewOrder.reviewOrder", + "description": "批量审核通过订单并进入待处理。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "订单 ID 数组;仅允许 ids 字段,建议传数组,也兼容逗号字符串或单值" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" + }, + { + "name": "inspection_status", + "type": "string", + "required": true, + "description": "新的审核状态" + }, + { + "name": "step", + "type": "number", + "required": true, + "description": "新的流程步骤" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间" + }, + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" + }, + { + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "description": "ids 不能为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + } + ] + }, + { + "groupName": "订单待处理模块", + "module": "order.pendingOrder", + "list": [ + { + "method": "order.pendingOrder.list", + "description": "待处理订单列表,默认筛选 outbound_status != padding 且 step in [1,2]。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.pendingOrder.reverseReviewOrder", + "description": "将待处理订单反审回待审核状态。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "订单 ID 列表;兼容 ids / id / order_id,建议传 ids" }, { "name": "id", "type": "number", "required": false, "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.listItems", - "description": "查询订单商品明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" + "description": "兼容单个订单 ID" }, { "name": "order_id", "type": "number", "required": false, "source": "body", - "description": "order_id 参数" + "description": "兼容单个订单 ID" } ], - "response": [], - "errors": [] - }, - { - "method": "order.stats", - "description": "订单统计", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;统计口径与 order.list 共用筛选字段。示例:where.status={operator:eq,value:fin}; where.create_time_start={value:2026-03-01}; where.create_time_end={value:2026-03-31}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.getreviewOrderlist", - "description": "分页查询订单审核列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、step、operator_name、operate_time_start、operate_time_end 等字段。示例:where.step={operator:in,value:[0,1]}; where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.updateStatus", - "description": "更新订单状态", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "claim_status", - "type": "string", - "required": false, - "source": "body", - "description": "claim_status 参数" - }, - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "delivery_time", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_time 参数" - }, + "response": [ { "name": "id", "type": "number", - "required": false, - "source": "body", - "description": "id 参数" + "required": true, + "description": "首条更新记录 ID" }, { "name": "inspection_status", "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数" + "required": true, + "description": "新的审核状态" }, { - "name": "intercept_status", - "type": "string", - "required": false, - "source": "body", - "description": "intercept_status 参数" + "name": "step", + "type": "number", + "required": true, + "description": "新的流程步骤" }, { - "name": "lock_status", + "name": "updated_at", "type": "string", - "required": false, + "required": true, + "description": "更新时间" + }, + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" + }, + { + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "description": "订单ID 不能为空或格式错误" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + }, + { + "method": "order.pendingOrder.markPendingOutboundOrder", + "description": "将待处理订单批量标记为待出库。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, "source": "body", - "description": "lock_status 参数" + "description": "订单 ID 正整数数组;不支持 id、order_id 或逗号字符串" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" }, { "name": "outbound_status", "type": "string", - "required": false, - "source": "body", - "description": "outbound_status 参数" + "required": true, + "description": "新的出库状态" }, { - "name": "pack_status", + "name": "updated_at", "type": "string", - "required": false, - "source": "body", - "description": "pack_status 参数" + "required": true, + "description": "更新时间" }, { - "name": "pick_status", - "type": "string", - "required": false, - "source": "body", - "description": "pick_status 参数" + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" }, { - "name": "post_status", - "type": "string", - "required": false, - "source": "body", - "description": "post_status 参数" + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" + } + ], + "errors": [ + { + "code": "400", + "description": "ids 必须为正整数数组" }, { - "name": "print_status", + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + }, + { + "method": "order.pendingOrder.cancelOrder", + "description": "将待处理订单批量取消,仅允许当前状态可取消的订单。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", "type": "string", - "required": false, + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, "source": "body", - "description": "print_status 参数" + "description": "订单 ID 正整数数组;不支持 id、order_id 或逗号字符串" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "首条更新记录 ID" }, { "name": "status", "type": "string", - "required": false, - "source": "body", - "description": "status 参数" + "required": true, + "description": "新的订单状态" }, { - "name": "storage_status", + "name": "step", + "type": "number", + "required": true, + "description": "新的流程步骤" + }, + { + "name": "updated_at", "type": "string", - "required": false, - "source": "body", - "description": "storage_status 参数" + "required": true, + "description": "更新时间" + }, + { + "name": "updated_count", + "type": "number", + "required": true, + "description": "受影响行数" + }, + { + "name": "ids", + "type": "array", + "required": true, + "description": "实际更新的订单 ID 列表" } ], - "response": [], - "errors": [] - }, + "errors": [ + { + "code": "400", + "description": "ids 必填或当前状态不允许取消" + }, + { + "code": "404", + "description": "订单不存在或不属于当前仓库" + } + ] + } + ] + }, + { + "groupName": "订单待出库模块", + "module": "order.outboundOrder", + "list": [ { - "method": "order.updateDeliveryTime", - "description": "更新发货时间", + "method": "order.outboundOrder.list", + "description": "待出库订单列表,默认筛选 outbound_status in [none,padding] 且 step in [1,2]。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -838,19 +1260,55 @@ ], "params": [ { - "name": "delivery_time", - "type": "string", - "required": true, + "name": "pagination", + "type": "object", + "required": false, "source": "body", - "description": "delivery_time 参数" + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] }, { - "method": "order.reviewOrder", - "description": "订单审核", + "method": "order.outboundOrder.manualOutboundOrder", + "description": "待出库模块的手动出库入口,行为与 order.manualOutboundOrder 一致。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -863,146 +1321,104 @@ ], "params": [ { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", + "name": "warehouseId", "type": "number", "required": false, "source": "body", - "description": "id 参数" + "description": "单仓库ID,兼容 warehouse_id" }, { - "name": "inspection_status", - "type": "string", + "name": "warehouseIds", + "type": "array", "required": false, "source": "body", - "description": "inspection_status 参数(兼容入参)" + "description": "仓库ID 数组" }, { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.getreviewOrderlist", - "description": "分页查询订单审核列表(目录化路由)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、step、operator_name、operate_time_start、operate_time_end 等字段。示例:where.step={operator:in,value:[0,1]}; where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.reviewOrder", - "description": "订单审核(目录化路由)。执行后会更新 inspection_status,并同步更新订单整数字段 step。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", + "name": "queryTimeoutMs", "type": "number", "required": false, "source": "body", - "description": "id 参数" + "description": "查询超时时间(毫秒)" }, { - "name": "inspection_status", - "type": "string", + "name": "executionTimeoutMs", + "type": "number", "required": false, "source": "body", - "description": "inspection_status 参数(兼容入参)" - }, - { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" + "description": "执行超时时间(毫秒)" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "warehouseIds", + "type": "array", + "required": true, + "description": "参与迁移的仓库ID列表" + }, + { + "name": "batchSize", + "type": "number", + "required": true, + "description": "单批处理上限,当前固定为 1000" + }, + { + "name": "outboundStatuses", + "type": "array", + "required": true, + "description": "本次迁移匹配的出库状态" + }, + { + "name": "totalSelected", + "type": "number", + "required": true, + "description": "命中的源订单数量" + }, + { + "name": "totalCreated", + "type": "number", + "required": true, + "description": "实际创建到配送表的订单数量" + }, + { + "name": "totalSkipped", + "type": "number", + "required": true, + "description": "本次跳过的源订单数量" + }, + { + "name": "totalTimeout", + "type": "number", + "required": true, + "description": "被标记为出库超时的订单数量" + }, + { + "name": "results", + "type": "array", + "required": true, + "description": "按仓库维度返回的批次结果数组,元素包含 selectedCount、createdCount、skippedCount、timeoutCount、retryableFailure 等字段" + } + ], + "errors": [ + { + "code": "400", + "description": "仓库ID为空或请求参数格式错误" + }, + { + "code": "500", + "description": "迁移失败或数据库错误" + } + ] + } + ] + }, + { + "groupName": "订单异常模块", + "module": "order.expectionOrder", + "list": [ { - "method": "order.deliveryOrder.getdeliveryOrderlist", - "description": "分页查询已进入出库流程的订单列表", + "method": "order.expectionOrder.list", + "description": "待处理异常订单列表,默认仅查询 step=3 的订单。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1019,22 +1435,57 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status != none;支持 step 筛选。示例:where.outbound_status={operator:in,value:[created,processing]}; where.step={operator:in,value:[4,5]}; where.store_id={operator:eq,value:1001}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单委托外仓模块", + "module": "order.entrustOrder", + "list": [ { - "method": "order.pendingOrder.getpendingOrderlist", - "description": "分页查询待处理订单列表", + "method": "order.entrustOrder.list", + "description": "委托外仓订单列表,使用 outsourced 模型。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1051,22 +1502,57 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认 status in [pedding, created] 且 outbound_status = none。示例:where.status={operator:in,value:[pedding,created]}; where.outbound_status={operator:eq,value:none}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单配送模块", + "module": "order.deliveryOrder", + "list": [ { - "method": "order.expectionOrder.getexpectionOrderlist", - "description": "分页查询异常订单列表", + "method": "order.deliveryOrder.list", + "description": "配送订单列表,使用 dispatch 模型,默认筛选 dispatch_lane=m4。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1083,22 +1569,57 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认筛选各流程 error 或拦截 exception。示例:where.status={operator:eq,value:error}; where.outbound_status={operator:eq,value:exception}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] - }, + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单配送异常模块", + "module": "order.deliveryExpectionOrder", + "list": [ { - "method": "order.archiveOrder.getarchiveOrderlist", - "description": "分页查询归档订单列表(暂使用当前订单表完成态数据)", + "method": "order.deliveryExpectionOrder.list", + "description": "配送异常订单列表,使用 dispatch 模型,默认筛选 dispatch_lane=m5。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -1115,18 +1636,114 @@ "type": "object", "required": false, "source": "body", - "description": "pagination 参数" + "description": "分页参数,支持 page / pageSize" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status = fin。示例:where.outbound_status={operator:eq,value:fin}; where.store_id={operator:eq,value:1001}。" + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] + } + ] + }, + { + "groupName": "订单归档模块", + "module": "order.archiveOrder", + "list": [ + { + "method": "order.archiveOrder.list", + "description": "归档订单列表,使用 history 模型。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;禁止传入 warehouse_id / warehouseId。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField / sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "订单列表(raw 行数据)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息" + } + ], + "errors": [ + { + "code": "400", + "description": "参数格式错误或缺少仓库上下文" + }, + { + "code": "500", + "description": "查询失败" + } + ] } ] }, @@ -3008,6 +3625,31 @@ "type": "object", "description": "关联的货主签约信息(LEFT JOIN),含 store_id、store_remask;无签约时为 null" }, + { + "name": "is_shelf_life_mgmt", + "type": "boolean", + "description": "是否启用效期管理(true=启用)" + }, + { + "name": "shelf_life_days", + "type": "number", + "description": "商品标准效期/保质期(单位:天)" + }, + { + "name": "inbound_min_days", + "type": "number", + "description": "入库后最小可出库天数(单位:天)" + }, + { + "name": "outbound_min_days", + "type": "number", + "description": "出库前需保留的最小天数(单位:天)" + }, + { + "name": "remaining_threshold_days", + "type": "number", + "description": "剩余天数阈值,低于该值视为即将过期(单位:天)" + }, { "name": "storage", "type": "array", @@ -3247,8 +3889,8 @@ ] }, { - "groupName": "库存模块", - "module": "storage", + "groupName": "收货单模块", + "module": "storage_receiving", "list": [ { "method": "storage.receiving.getReceivingList", @@ -3761,7 +4403,7 @@ }, { "method": "storage.receiving.detailChange", - "description": "storage.receiving.detailChange 接口", + "description": "修改收货单明细(数量/箱规/批次/商品信息回写等)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3772,9 +4414,192 @@ "description": "Bearer token" } ], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货明细ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "actual_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "实际收货数量" + }, + { + "name": "batch_number", + "type": "string", + "required": false, + "source": "body", + "description": "批次号" + }, + { + "name": "production_date", + "type": "string", + "required": false, + "source": "body", + "description": "生产日期(可解析的日期字符串)" + }, + { + "name": "expiry_date", + "type": "string", + "required": false, + "source": "body", + "description": "到期日期(可解析的日期字符串)。若早于当前日期,接口会返回 400 并拒绝录入。" + }, + { + "name": "box_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "箱数" + }, + { + "name": "boxes_per_pallet", + "type": "number", + "required": false, + "source": "body", + "description": "每托盘箱数" + }, + { + "name": "pallet_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "托盘数" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "source": "body", + "description": "库位 ID(可回写)" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "system_product_id", + "type": "number", + "required": false, + "source": "body", + "description": "系统商品 ID(StockWarehouse.id)。若提供,服务端会尝试回填 barcode/weight/箱规/product_name/product_snapshot 等。" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "条码(未传 system_product_id 时可单独更新)" + }, + { + "name": "product_name", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称(未传 system_product_id 时可单独更新)" + }, + { + "name": "box_width", + "type": "number", + "required": false, + "source": "body", + "description": "箱宽" + }, + { + "name": "box_height", + "type": "number", + "required": false, + "source": "body", + "description": "箱高" + }, + { + "name": "box_length", + "type": "number", + "required": false, + "source": "body", + "description": "箱长" + }, + { + "name": "weight", + "type": "number", + "required": false, + "source": "body", + "description": "毛重/重量" + } + ], + "response": [ + { + "name": "data.id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "data.receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "data.actual_quantity", + "type": "number", + "required": false, + "description": "实际收货数量" + }, + { + "name": "data.product_name", + "type": "string", + "required": false, + "description": "商品名称" + }, + { + "name": "data.barcode", + "type": "string", + "required": false, + "description": "条码" + }, + { + "name": "data.system_product_id", + "type": "number", + "required": false, + "description": "系统商品 ID" + }, + { + "name": "data.updated_at", + "type": "string", + "required": false, + "description": "记录更新时间(ISO)" + } + ], + "errors": [ + { + "code": "400", + "description": "收货明细ID不能为空 / 收货单ID不能为空 / 到期日期已过期,不能录入收货 / 箱数/托盘数不能为负数等参数校验失败" + }, + { + "code": "404", + "description": "收货明细不存在或无权访问" + }, + { + "code": "500", + "description": "服务器错误或修改失败" + } + ] }, { "method": "storage.receiving.cancel", @@ -4245,12 +5070,30 @@ ] }, "errors": [ - { "code": 400, "message": "receiving_id 必填" }, - { "code": 400, "message": "收货单状态须为已完成" }, - { "code": 400, "message": "商品未匹配系统商品" }, - { "code": 400, "message": "已全部入库无需重复操作" }, - { "code": 404, "message": "收货单不存在或无权访问" }, - { "code": 409, "message": "库存记录被锁定(行锁超时)" } + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 400, + "message": "收货单状态须为已完成" + }, + { + "code": 400, + "message": "商品未匹配系统商品" + }, + { + "code": 400, + "message": "已全部入库无需重复操作" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 409, + "message": "库存记录被锁定(行锁超时)" + } ] }, { @@ -4296,10 +5139,22 @@ "warnings": "匹配过程中的警告信息列表" }, "errors": [ - { "code": 400, "message": "receiving_ids 必填且为数组" }, - { "code": 400, "message": "entry_order_ids 必填且为数组" }, - { "code": 404, "message": "收货单不存在或无权访问" }, - { "code": 404, "message": "入库单不存在或无权访问" } + { + "code": 400, + "message": "receiving_ids 必填且为数组" + }, + { + "code": 400, + "message": "entry_order_ids 必填且为数组" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 404, + "message": "入库单不存在或无权访问" + } ] }, { @@ -4339,12 +5194,30 @@ "message": "结果说明" }, "errors": [ - { "code": 400, "message": "storage_id 必填" }, - { "code": 400, "message": "target_space_id 必填" }, - { "code": 400, "message": "移库数量必须大于0且不超过可用库存" }, - { "code": 400, "message": "目标库位与原库位相同" }, - { "code": 404, "message": "库存记录不存在或无权访问" }, - { "code": 404, "message": "目标库位不存在或不属于该仓库" } + { + "code": 400, + "message": "storage_id 必填" + }, + { + "code": 400, + "message": "target_space_id 必填" + }, + { + "code": 400, + "message": "移库数量必须大于0且不超过可用库存" + }, + { + "code": 400, + "message": "目标库位与原库位相同" + }, + { + "code": 404, + "message": "库存记录不存在或无权访问" + }, + { + "code": 404, + "message": "目标库位不存在或不属于该仓库" + } ] }, { @@ -4423,6 +5296,7 @@ ], "response": { "_note": "响应结构因 group_by_batch 而异", + "_shelf_life_note": "production_date 和 expiry_date 为库存批次日期字段;is_shelf_life_warning_triggered 表示该库存在商品启用保质期管理且剩余天数小于等于阈值时是否触发效期预警。", "list_merged": { "_description": "group_by_batch=false(默认合并模式)", "list": [ @@ -4438,11 +5312,30 @@ "first_inbound_time": "最早入库时间", "last_inbound_time": "最晚入库时间", "batch_count": "批次数", - "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, - "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + "production_date": "生产日期(库存批次日期字段,合并模式下可能为 null)", + "expiry_date": "过期日期(库存批次日期字段,合并模式下可能为 null)", + "is_shelf_life_warning_triggered": "布尔,表示效期预警是否触发(仅在商品启用保质期管理且剩余天数 ≤ 阈值时为 true)", + "stock": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位", + "store_name": "货主名称(来源于签约表 store_remask,若无签约关系则为 null)" + }, + "space": { + "id": "库位ID", + "space_code": "库位编码", + "custom_name": "库位名称" + } } ], - "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + "pagination": { + "page": 1, + "pageSize": 20, + "total": 100, + "totalPages": 5 + } }, "list_detail": { "_description": "group_by_batch=true(明细模式)", @@ -4458,8 +5351,8 @@ "quantity": "库存数量", "locked_quantity": "锁定数量", "available_quantity": "可用数量", - "production_date": "生产日期", - "expiry_date": "过期日期", + "production_date": "生产日期(库存批次日期字段)", + "expiry_date": "过期日期(库存批次日期字段)", "inbound_time": "入库时间", "inbound_order_no": "入库单号", "receiving_id": "收货单ID", @@ -4467,14 +5360,167 @@ "supplier_batch_no": "供应商批次号", "created_at": "创建时间", "updated_at": "更新时间", - "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, - "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + "is_shelf_life_warning_triggered": "布尔,表示效期预警是否触发(仅在商品启用保质期管理且剩余天数 ≤ 阈值时为 true)", + "stock": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位", + "store_name": "货主名称(来源于签约表 store_remask,若无签约关系则为 null)" + }, + "space": { + "id": "库位ID", + "space_code": "库位编码", + "custom_name": "库位名称" + } } ], - "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + "pagination": { + "page": 1, + "pageSize": 20, + "total": 100, + "totalPages": 5 + } } } }, + { + "method": "storage.expiry.list", + "description": "库存有效期列表查询(效期预警),按 wms_storage 查询并计算剩余天数与过期状态,支持 where 条件与分页。注意:无需传 warehouse_id/store_id,服务端会从当前登录用户取仓库上下文。", + "name": "库存有效期列表(或:库存效期预警列表)", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;支持字段:item_code、goods_code、item_name、sku_property、stock_unit、is_shelf_life_mgmt、remaining_threshold_days。示例:where.item_code={operator:like,value:ABC}; where.remaining_threshold_days={operator:lte,value:7}。注意:无需传入 store_id 或 warehouse_id,服务端会从当前登录用户获取仓库上下文。" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "匹配到的库存效期项数组" + }, + { + "name": "data.list[]", + "type": "object", + "description": "列表项,包含至少以下字段", + "children": [ + { + "name": "id", + "type": "number", + "description": "库存记录ID(wms_storage.id)" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量" + }, + { + "name": "expiry_date", + "type": "string", + "description": "过期/到期日期(ISO)" + }, + { + "name": "remaining_days", + "type": "number", + "description": "距到期剩余天数(正数表示未过期,0 当日到期,负数表示已过期)" + }, + { + "name": "threshold_days", + "type": "number", + "description": "阈值天数,优先使用传入 remaining_threshold_days,否则使用商品配置" + }, + { + "name": "is_expired", + "type": "boolean", + "description": "是否已过期(true=已过期)" + }, + { + "name": "stock", + "type": "object", + "description": "关联商品信息(id、item_code、item_name、sku_property、stock_unit 等)" + }, + { + "name": "space", + "type": "object", + "description": "关联库位信息(id、space_code、custom_name 等)" + }, + { + "name": "created_at", + "type": "string", + "description": "记录创建时间" + }, + { + "name": "updated_at", + "type": "string", + "description": "记录更新时间" + }, + { + "name": "inbound_time", + "type": "string", + "description": "入库时间" + }, + { + "name": "production_date", + "type": "string", + "description": "生产日期" + } + ] + }, + { + "name": "data.pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages" + } + ], + "errors": [ + { + "code": 400, + "message": "where 条件格式不正确" + } + ] + }, { "method": "storage.transaction.list", "description": "出入库记录列表查询,支持 where 条件、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", @@ -4538,7 +5584,12 @@ } } ], - "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + "pagination": { + "page": "当前页", + "pageSize": "每页条数", + "total": "总记录数", + "totalPages": "总页数" + } }, "list_detail": { "_description": "group_by_batch=true(明细模式)", @@ -4572,12 +5623,23 @@ } } ], - "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + "pagination": { + "page": "当前页", + "pageSize": "每页条数", + "total": "总记录数", + "totalPages": "总页数" + } } }, "errors": [ - { "code": 400, "message": "where 条件格式不正确" }, - { "code": 400, "message": "分页参数不合法" } + { + "code": 400, + "message": "where 条件格式不正确" + }, + { + "code": 400, + "message": "分页参数不合法" + } ] } ] @@ -4588,7 +5650,7 @@ "list": [ { "method": "store.createStore", - "description": "store.createStore 接口", + "description": "store.createStore 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -4599,13 +5661,42 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "subject_config", + "type": "object", + "required": false, + "source": "body", + "description": "货主主体配置,不传时自动写入默认值" + }, + { + "name": "subject_config.max_notice_webhook_count", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "当前主体最多允许绑定 / 触达的消息推送接口数量,默认 5" + }, + { + "name": "subject_config.default_express_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认快递编码,缺省为 STO" + }, + { + "name": "subject_config.default_platform_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认平台编码,缺省为 TB" + } + ], "response": [], "errors": [] }, { "method": "store.createWarehouse", - "description": "store.createWarehouse 接口", + "description": "store.createWarehouse 接口,subject_config 未传时默认写入 max_notice_webhook_count=5、default_express_code=STO、default_platform_code=TB", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -4616,7 +5707,36 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "subject_config", + "type": "object", + "required": false, + "source": "body", + "description": "货主主体配置,不传时自动写入默认值" + }, + { + "name": "subject_config.max_notice_webhook_count", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "当前主体最多允许绑定 / 触达的消息推送接口数量,默认 5" + }, + { + "name": "subject_config.default_express_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认快递编码,缺省为 STO" + }, + { + "name": "subject_config.default_platform_code", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "默认平台编码,缺省为 TB" + } + ], "response": [], "errors": [] }, @@ -5186,7 +6306,7 @@ "type": "object", "required": true, "source": "body", - "description": "策略配置对象;仅支持 receive_mode、sku_visibility、auto_allocate_bin、allow_mix_batch、allow_temp_storage、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" + "description": "策略配置对象;仅支持 receive_mode、auto_allocate_bin、allow_mix_batch、allow_temp_storage、storage_separation、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" } ], "response": [], @@ -6329,4 +7449,5 @@ } ] } -} + +} \ No newline at end of file diff --git a/order_todo.md b/order_todo.md index 9aaba93..e3119ec 100644 --- a/order_todo.md +++ b/order_todo.md @@ -74,7 +74,7 @@ --- -## 1. 目标与范围(含 M7) +## 1. 目标与范围(含 outsourced) ### 1.1 工作台模块一览 @@ -83,18 +83,18 @@ | M1 待审核 | 需审核后进入后续履约 | **仅 current** | | M2 待处理 | 仓内/出库前正常队列 | **仅 current** | | M3 待处理异常 | 出库前各环节异常 | **仅 current** | -| M4 配送订单 | 配送链路正常态 | **配送域工厂(待建)**,约 3 自然月 | -| M5 配送异常 | 配送链路异常(M4 子集) | **同上** | +| M4 配送订单 | 配送链路正常态 | **配送域工厂(首期已落地)**:单表 `wms_order_delivery_dispatch_{wh}` + 列 `dispatch_lane=m4`;**不按自然月拆物理表** | +| M5 配送异常 | 配送链路异常(M4 子集) | **同上表**,`dispatch_lane=m5` 筛选;归档/近三月策略走 **查询与任务**,不必多分表 | | M6 归档订单 | 冷数据 | **history**(>3 月等策略) | -| **M7 外仓发货** | 本仓不履约、推送外仓/三方履约;**暂无完整状态机** | **可与 current 扩展标记 + 外仓任务表** 或独立子域(待设计) | +| **outsourced 外仓发货** | 本仓不履约、推送外仓/三方履约;**已纳入 `OrderDeliveryFactory` 管理的 managed table / schema self-check 体系** | **由工厂统一管理,启动自检自动对齐结构**;仍可结合 current 扩展标记 + 外仓任务表落地 | ### 1.2 数据分层(与 §0 对齐) | 层级 | 表 / 模型 | 时间 / 策略 | |------|-----------|-------------| -| 热区 M1~M3 / M7(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) | -| 配送区 M4/M5 | **配送域工厂**(独立于 current 的强分区存储) | **按自然月**;滚动 **3 个自然月** | -| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/M7 **不走 M6 物理归档路径**(见 §2.4) | +| 热区 M1~M3 / outsourced(规划) | `wms_order_delivery_{wh}`、`wms_order_items_{wh}`(current) | 当日或未闭环;**创建时分流 M1 vs M2 由货主配置决定**;**到期仅克隆续单**,不进 M6(§2.4) | +| 配送区 M4/M5 | **`wms_order_delivery_dispatch_{wh}`**(`OrderDeliveryFactory` 的 dispatch 模式) | **单物理表**;M4/M5 用 **`dispatch_lane`**;**不按自然月拆表**;「约 3 个月」保留为 **列表/归档任务的时间条件**(见 §2.5 落地说明) | +| 冷数据 M6 | `*_history`(仅承接 **M4/M5** 迁入) | **超过 3 个月**等策略;**仅允许 M4/M5 进入 M6**;M1/M2/M3/outsourced **不走 M6 物理归档路径**(见 §2.4) | --- @@ -103,16 +103,16 @@ ### 2.1 订单创建:进入 M1 或 M2 - **规则**:创建时读取 **货主(store)配置**,决定初始进入 **M1(待审核)** 或 **M2(待处理)**。 -- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 M7(外仓发货)** 路径之一;具体字段与接口待定义。 -- **M2 ⊥ M7(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/M7 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。 -- **M7**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。 +- **M1 → M2**:必须通过 **仓内库存校验**(满足可履约)**或** 选择 **推送 outsourced(外仓发货)** 路径之一;具体字段与接口待定义。 +- **M2 ⊥ outsourced(强制互斥)**:同一订单 **不得** 同时处于本仓待处理与外仓履约;进入或退出 M2/outsourced 的切换 **必须在单条(或可串行化的)数据库事务内完成**(状态位 + 外仓任务表等一并提交),失败 **整体回滚**,禁止半开状态。 +- **outsourced**:当前 **无完整状态机**;与 M4 的衔接仍遵守 §2.2 单向规则。 ### 2.2 进入 M4 的约束(核心) | 从 → 到 | 是否允许 | 说明 | |---------|----------|------| -| **M2 → M4** | **允许(单向)** | M2、**M7 仅允许单向落入 M4** | -| **M7 → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 | +| **M2 → M4** | **允许(单向)** | M2、**outsourced 仅允许单向落入 M4** | +| **outsourced → M4** | **允许(单向)** | 外仓发货完成后,依赖 **外部通知** 与出库状态机推进 | | **M1 → M4** | **禁止** | 须先 **切到 M2** 且 **状态机到达出库** 后,再经 **外部通知发货完成** 落入 M4 | | **M3 → M4** | **禁止** | 须先 **消除异常并回到 M2**,再走与 M2 相同路径进入 M4 | | **取消订单 → M4** | **允许(专用)** | 见 **§2.3a**:标记取消态后 **直进 M4**,**不可逆**、**零例外** | @@ -120,7 +120,7 @@ ### 2.3 M4 / M5 与外部机制 - **M4 ↔ M5 切换**:由 **外部机制** 驱动(承运商回传、网关、人工标记等),不在此文档展开协议。 -- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/M7 与 M4/M5 不重复占位**:**M1~M3(及 M7)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。 +- **M4/M5 与 M1~M3**:除下节「补发副本」外,**同一订单在 M1/M2/M3/outsourced 与 M4/M5 不重复占位**:**M1~M3(及 outsourced)为唯一工作台态**;**M4/M5 为配送域单独态**(可理解为 **配送域一条影子/主数据**,与 current 热行通过 `order_id` / `delivery_order_code` / 快照关联)。 ### 2.3a 订单取消(特殊路径:标记后进 M4) @@ -132,14 +132,15 @@ - **时间策略**:**所有订单类型均受时间维度约束,不另开例外**;**进入 M6(物理归档)后不可逆**,**不允许任何例外**(不设司法解冻、不设未归档回退通道)。 - **谁可以进 M6(物理)**:**仅 M4、M5** 对应的配送域数据(及与其绑定的明细快照)允许在满足保留期后 **迁入 `history` / 冷存储**。 -- **谁不可以进 M6**:**M1、M2、M3、M7** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。 +- **谁不可以进 M6**:**M1、M2、M3、outsourced** 热区行 **不允许** 走与 M4/M5 **相同的** M6(history)迁入通道;**到期后仅允许「克隆续单」**:通过 **新行(新主键)** 承接后续履约,原行 **仅改标记**(§2.7),**不得**删/软删、**不得**将原行迁入 M6。 - **克隆续单 / 补单(首期)**:**不与奇门等平台同步**;定位为 **补单**,由 **人工在仓内/运营侧处理**;系统可提供列表与标记能力,**接口与对账范围以本仓 WMS 为准**。 - **M4/M5 → M6**:以 **出库时间**(如 `delivery_time` / 出库确认时间)为主键条件之一,满足 **>3 个月**(与 §1.2 口径对齐)后迁入 history;过程 **不可逆**。 -### 2.5 配送域工厂(规划) +### 2.5 配送域工厂(首期落地 + 后续) -- **单独工厂**:M4/M5 **不共用** `OrderDeliveryFactory` 的 current 物理表;新建 **配送域工厂**,**model 定义仍由工厂类统一加载/缓存/分表键管理**(与现有工厂模式一致),**事务边界与分区键强绑定**(**事务驱动强分区**:单事务内读写同一分区键,如 `warehouseId + yyyyMM`)。 -- **自然月**:表名或 MySQL PARTITION 与 **自然月** 对齐,保留 **3 个自然月** 滚动窗口。 +- **已实现**:`app/model/order_delivery_factory.js` 的 dispatch 模式;物理表 **`wms_order_delivery_dispatch_{warehouseId}`**(与热区 `wms_order_delivery_{wh}` 命名同族,中间段 **`dispatch`**);**M4/M5 同表**,列 **`dispatch_lane` ENUM('m4','m5')** 区分;**不按自然月拆物理表**。`getDispatchModel(wh)` 为主入口;`getM4Model`/`getM5Model` 复用同一 dispatch 模式返回 **同一模型**。**outsourced 也已经纳入同一工厂管理,应用启动时会通过自检自动对齐 managed table 结构**。 +- **单测**:`test/app/model/order_delivery_dispatch_factory.test.js`;需连库时 `DISPATCH_FACTORY_TEST_MYSQL=1`(见 `config/plugin.js`);留表排查 `KEEP_DISPATCH_FACTORY_TABLES=1`。 +- **仍待**:与 current 的 **副本同步 / 事件驱动**;**强分区事务** 口径改为「单事务内同一 `warehouse_id` + 配送域表」即可(不再绑定 `yyyyMM` 表名);`wms_order_express` 与配送域行关联方案;M6 迁入仍以 **出库时间 + 保留期** 驱动(§2.4)。 ### 2.6 M4/M5 副本回归 M1 / M2 / M3(补发 / 部分履约) @@ -160,9 +161,9 @@ |------|------| | M1 ⊥ (M2 ∪ M3) | 不变 | | M2 ⊥ M3 | 不变 | -| **M2 ⊥ M7** | **强制互斥**;切换须 **事务**(§2.1) | +| **M2 ⊥ outsourced** | **强制互斥**;切换须 **事务**(§2.1) | | M5 ⊆ M4 | 不变 | -| **M1~M3 / M7(热区)** | **同一订单唯一展示态**(互斥集合内择一) | +| **M1~M3 / outsourced(热区)** | **同一订单唯一展示态**(互斥集合内择一) | | **M4 / M5** | **配送域内**可与热区并存为 **影子数据**;列表层需约定「主工作台只显示一侧」避免重复操作 | | **M6** | **仅 M4/M5 可物理迁入**;**不可逆、零例外**;热区到期 **不进 M6**,**仅允许克隆续单**(§2.4) | @@ -172,12 +173,12 @@ ### 3.1 列表查询(各模块) -**目标**:最小可用字段集 + **足够前端判断订单状态**(含 M7 外仓标记若存在)。 +**目标**:最小可用字段集 + **足够前端判断订单状态**(含 outsourced 外仓标记若存在)。 **原则**: - 列表不返回大体积 `items` TEXT;仅标识、各 `*_status`、`outbound_status`、`inspection_status`、`step`、`updated_at` / `delivery_time`、货主/仓编码等。 -- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/M7 在配送域或扩展表就绪后各自维护一份。 +- 实现:**按模块常量 `LIST_FIELDS`**;M4/M5/outsourced 在配送域或扩展表就绪后各自维护一份。 ### 3.2 明细查询 @@ -206,35 +207,38 @@ | 2026-04-10 | **无业务代码 / 无 migration 变更**。新增只读交付物:`docs/order-cancel-db-checklist.md`(§0.7 跑库步骤)、`docs/order-state-machine-dictionary.md`(状态机字典 **v0 骨架**,与 `app/model/order_delivery.js` 摘录一致)。**数仓映射、实际跑库结果** 仍待下一小阶段。 | | 2026-04-10 | **小阶段 A-1(影响面)**:新增 `docs/order-delivery-migration-impact.md`。**结论**:在未跑库确认缺列、且未敲定「取消进 M4」专用列前,**不自动提交 ALTER migration**;若清单验证列已齐,可先 **零表变更** 做应用筛选。详见该文档 **§1**。 | | 2026-04-10 | **小阶段 A-2(wms-db-agent 只读诊断)**:已对 `wms` 库跑清单;结果写入 **`docs/order-cancel-db-checklist.md` §5**。要点:**分表** `100000`/`1000028` 目标列齐全,可先不增列做筛选;**基表**缺三列、**勿**当业务表用;**无 `_history` 样本**;`chcp 65001` 防 JSON 解析失败。 | +| 2026-04-11 | **基表状态列**:migration `20260410200000-add-status-columns-to-wms-order-delivery-base.js`(按需补列,与热区分表对齐)。**配送域**:`OrderDeliveryFactory` 的 dispatch 模式单表 `wms_order_delivery_dispatch_{wh}` + `dispatch_lane`;当前按单表落地,不再保留「m4/m5 分表 + 自然月表名」方案;单测与 `DISPATCH_FACTORY_TEST_MYSQL` 见上文 §2.5。 | +| 2026-04-11 | **outsourced 收敛**:`outsourced` 纳入 `OrderDeliveryFactory` 的 managed table / schema self-check 体系,沿用启动自检自动对齐结构;旧兼容 shim 已移除,文档与代码统一收口到工厂管理。 | ### 阶段 A — 文档与规则冻结 -- [ ] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。 -- [ ] M1→M2:库存校验 API、M7 推送接口与回写字段。 +- [x] 货主配置:「创建进 M1 / M2」的配置项落库位置与变更流程。 +- [ ] M1→M2:库存校验 API、outsourced 推送接口与回写字段。 - [ ] 外部「发货完成」通知与状态机字段的映射表(落到 `outbound_status` / `step` 等)。 - [x] **§0.7 清单文档**:`docs/order-cancel-db-checklist.md`(各环境人工执行)。 - [x] **§0.7 跑库(本机 wms 一次)**:见 `docs/order-cancel-db-checklist.md` §5;**分表列齐**;**其它仓/生产须复跑**。 -- [ ] **§0.7 缺列 migration**:若产品仍要独立「取消进 M4」列或基表对齐,再开 migration;更新模型与工厂 DDL。 +- [x] **§0.7 基表状态列 migration**(与分表枚举对齐):`database/migrations/20260410200000-add-status-columns-to-wms-order-delivery-base.js`(已合并进仓库;其它环境须自行 `db:migrate`)。**独立「取消进 M4」业务列** 仍待产品定名后再 migration。 - [x] **状态机字典 v0 骨架**:`docs/order-state-machine-dictionary.md`(与数仓/报表的 **字段映射表** 仍待补)。 -- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(结论:**未自动做 migration**,待跑库 + 列名后由你决策)。 +- [x] **订单表 DDL 影响面分析**:`docs/order-delivery-migration-impact.md`(初版静态结论;**2026-04-11** 起基表状态列以已合并 migration 为准,文档全文若与现网不一致须择机修订)。 ### 阶段 B — 配送域工厂(3 自然月 + 强分区事务) -- [ ] 配送域工厂类设计(命名、目录、`app.js` 挂载)。 -- [ ] M4/M5 表结构、与 current 的 **副本同步** 或 **事件驱动** 方案。 -- [ ] `wms_order_express` 与配送域 **order_id + 分区键** 一致性方案。 +- [x] 配送域建表能力(`OrderDeliveryFactory` 的 dispatch 模式):表 **`wms_order_delivery_dispatch_{warehouseId}`**,**`dispatch_lane`** 区分 M4/M5。 +- [x] M4/M5 **单表** DDL 与动态模型(首期)。 +- [ ] 与 current 的 **副本同步** 或 **事件驱动** 方案(未做)。 +- [ ] `wms_order_express` 与配送域 **order_id**(及仓)一致性方案。 ### 阶段 C — 归档 M6 + 时间消除 - [ ] **仅 M4/M5**:配送域 → history 的 **出库时间** 驱动任务;**不可逆** 校验与审计(**零例外**)。 -- [ ] **M1/M2/M3/M7**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。 +- [ ] **M1/M2/M3/outsourced**:到期 **仅克隆续单** 流程(新行 + 原行标记);**禁止** 迁入 M6;前端 **空态/引导续单** 文案。 - [ ] **取消进 M4**:状态机字段字典、事务边界、与常规 M4 列表的 **展示分区**(避免与正常配送混淆)。 - [ ] 全库 **禁止 DELETE/软删** 副本与主单的 ORM/脚本审计;运维修正走 **状态机变更**(§2.7);**审批流** 见 **§5a 预留**。 ### 阶段 D — 补发副本与目标更新 - [ ] 补发单模型、原单引用、部分行、目标更新字段;**原行仅标记,禁止删/软删**。 -- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔M7 事务切换** 共用事务规范文档。 +- [ ] 事务:副本创建 + 热区插入 + 配送域标记 **同一强分区键内** 或可补偿 Saga;与 **M2↔outsourced 事务切换** 共用事务规范文档。 ### 阶段 E — API / 测试 @@ -273,11 +277,12 @@ | 日期 | 说明 | |------|------| | (首版) | 根据讨论整理计划草案 | -| 补充 | 增加 §0 当前表/模型/工厂/关联分析;M7、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 | -| 补充 | **M2⊥M7 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 | +| 补充 | 增加 §0 当前表/模型/工厂/关联分析;outsourced、创建分流、进入 M4 约束、外部驱动 M4/M5、时间进 M6、配送域独立工厂与强分区事务、M4/M5 按出库时间进 M6、补发副本回归 M1/2/3 | +| 补充 | **M2⊥outsourced 且事务进出**;**M6 仅 M4/M5 可物理迁入、不可逆**;热区到期不进 M6;**全副本禁止删/软删、仅标记或克隆**;§2.7 硬约束、§1.2/阶段 C/待补充项同步 | | 补充 | 热区到期 **仅克隆续单**;**§2.3a 取消→标记→直进 M4、不可逆零例外**;**运维「克隆」= 状态机合法变更** 写入 §2.2/§2.7/阶段 C | | 补充 | **§0.7** 取消状态机与分表核对/缺列 migration;**克隆续单不奇门同步、首期人工补单**;**字段字典与数仓报表同步**;**§5a 运维审批预留** | | 补充 | **§5 重写**:区分 **规则层已满足** vs **交付层未完成**;原 checklist 拆入 §5.1 / §5.2 并指向 §4 | | 2026-04-10 | **小阶段 A-0**:新增 `docs/order-cancel-db-checklist.md`、`docs/order-state-machine-dictionary.md`;§0.7 / §4 阶段 A / §5.2 同步;无代码变更 | | 2026-04-10 | **小阶段 A-1**:`docs/order-delivery-migration-impact.md`;**未提交 migration**(待你根据跑库 + 列名决策) | | 2026-04-10 | **小阶段 A-2**:wms-db-agent 只读诊断;`order-cancel-db-checklist.md` §5;**未提交 migration** | +| 2026-04-11 | **配送域单表工厂** + **基表 migration**;§1.2 / §2.5 / §4 阶段 B 勾选与表述同步 | diff --git a/package.json b/package.json index a43d04c..e2d159a 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,8 @@ "file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs", "debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs", "debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs", + "doc:api:update": "node ./script/update-api-doc.cjs", + "doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run", "deploy:init": "node ./script/deploy-init.cjs production", "deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run", "deploy:precheck": "node ./script/deploy-precheck.cjs", @@ -67,6 +69,7 @@ "setup:hooks": "node ./script/setup-git-hooks.cjs", "test": "npm run lint -- --fix && npm run test:local", "test:local": "egg-bin test", + "test:dispatch-factory": "egg-bin test test/app/model/order_delivery_dispatch_factory.test.js", "cov": "egg-bin cov", "lint": "eslint .", "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", diff --git a/runtime/file-writer/.write-window-counter-3.json b/runtime/file-writer/.write-window-counter-3.json index 809d98c..d37d073 100644 --- a/runtime/file-writer/.write-window-counter-3.json +++ b/runtime/file-writer/.write-window-counter-3.json @@ -1 +1 @@ -{"startedAt":1775826309321,"recordCount":2} +{"startedAt":1776007031826,"recordCount":1} diff --git a/runtime/file-writer/qimen-logs/.consume-progress b/runtime/file-writer/qimen-logs/.consume-progress index 641f604..93031fe 100644 --- a/runtime/file-writer/qimen-logs/.consume-progress +++ b/runtime/file-writer/qimen-logs/.consume-progress @@ -1,7 +1,7 @@ { - "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log", - "offset": 6149, - "processedCount": 2, - "completedAt": "2026-04-10T14:20:54.561Z", - "updatedAt": "2026-04-11T09:08:50.539Z" + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log", + "offset": 1713, + "processedCount": 1, + "completedAt": "2026-04-12T14:54:22.636Z", + "updatedAt": "2026-04-16T11:59:44.134Z" } diff --git a/runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp b/runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp new file mode 100644 index 0000000..4ebdee1 --- /dev/null +++ b/runtime/file-writer/qimen-logs/.consume-progress.25476.1775941895725.tmp @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\10\\qimen-logs-MINGREN-worker-p4496-0001.log", + "offset": 6149, + "processedCount": 2, + "completedAt": "2026-04-10T14:20:54.561Z", + "updatedAt": "2026-04-11T21:11:35.725Z" +} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log new file mode 100644 index 0000000..2b27332 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log @@ -0,0 +1 @@ +{"log_id":"QL-1776005200436-dfa9d6","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"74F6AD27E9412E9F1DABEBD72FBB0FD6","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005200&customerId=jky2025102001&sign=74F6AD27E9412E9F1DABEBD72FBB0FD6","created_at":"2026-04-12T14:46:40.436Z","body":"\n\n \n TRACE_OUTBOUND_1776005196546_B37AA0C5\n TAOBAO\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776005196546_B37AA0C5\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":92} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done new file mode 100644 index 0000000..809bc0c --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p38224-0001.log.done @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log", + "offset": 1713, + "processedCount": 1, + "completedAt": "2026-04-12T14:46:52.525Z", + "updatedAt": "2026-04-12T14:46:52.525Z" +} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log new file mode 100644 index 0000000..b1bbefa --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p41276-0001.log @@ -0,0 +1,4 @@ +{"log_id":"QL-1776005884434-818312","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"C591375BD641DD47560872675F5CCA0E","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005884&customerId=jky2025102001&sign=C591375BD641DD47560872675F5CCA0E","created_at":"2026-04-12T14:58:04.434Z","body":"\n\n \n TRACE_OUTBOUND_1776005880432_FA93FDAF\n TAOBAO\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776005880432_FA93FDAF\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":91} +{"log_id":"QL-1776006129287-77b8d4","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"A0B72528AC9B54B0DDA564298B20E7C0","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776006129&customerId=jky2025102001&sign=A0B72528AC9B54B0DDA564298B20E7C0","created_at":"2026-04-12T15:02:09.287Z","body":"\n\n \n TRACE_OUTBOUND_1776006125376_39EA41AC\n TB\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776006125376_39EA41AC\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":88} +{"log_id":"QL-1776006776809-5dbb53","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"65632055E9198D2C8E466A44D0EF0D4C","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776006776&customerId=jky2025102001&sign=65632055E9198D2C8E466A44D0EF0D4C","created_at":"2026-04-12T15:12:56.809Z","body":"\n\n \n TRACE_OUTBOUND_1776006772829_A0ADB113\n TB\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776006772829_A0ADB113\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":95} +{"log_id":"QL-1776007031740-155ce0","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"AE833C70C726B4B6664544B5A7B412EF","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776007031&customerId=jky2025102001&sign=AE833C70C726B4B6664544B5A7B412EF","created_at":"2026-04-12T15:17:11.740Z","body":"\n\n \n TRACE_OUTBOUND_1776007027818_0E2C252D\n TB\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776007027818_0E2C252D\n 510000\n \n \n \n \n 1000218\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":86} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log new file mode 100644 index 0000000..baf6200 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log @@ -0,0 +1 @@ +{"log_id":"QL-1776005653930-b9f1fa","from_key":"24869601","to_key":23535631,"method":"deliveryorder.create","sign":"4AB934D12D74B558BE1060D5525EFF7B","costomer_id":"jky2025102001","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=24869601&method=deliveryorder.create&v=2.0&format=xml&sign_method=md5×tamp=1776005653&customerId=jky2025102001&sign=4AB934D12D74B558BE1060D5525EFF7B","created_at":"2026-04-12T14:54:13.931Z","body":"\n\n \n TRACE_OUTBOUND_1776005649940_B0FA5A9A\n TAOBAO\n 淘宝\n 100000\n JYCK\n \n 自动化验证收件人\n 13800138000\n 广东省\n 广州市\n 黄埔区\n 知识城街道\n 自动化验证地址 TRACE_OUTBOUND_1776005649940_B0FA5A9A\n 510000\n \n \n \n \n 101391\n 023802\n 空包\n 1\n 1\n \n \n","result":"\n\n failure\n 0\n 奇门吉客云ERP客户编码jky2025102001仓库编码warehouseCode未绑定到你的货主或未启用,请联系仓库绑定\n","use_time":93} diff --git a/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done new file mode 100644 index 0000000..9a09ff1 --- /dev/null +++ b/runtime/file-writer/qimen-logs/2026/04/12/qimen-logs-MINGREN-worker-p42648-0001.log.done @@ -0,0 +1,7 @@ +{ + "filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p42648-0001.log", + "offset": 1713, + "processedCount": 1, + "completedAt": "2026-04-12T14:54:22.636Z", + "updatedAt": "2026-04-12T14:54:22.636Z" +} diff --git a/script/update-api-doc.cjs b/script/update-api-doc.cjs new file mode 100644 index 0000000..288cc9a --- /dev/null +++ b/script/update-api-doc.cjs @@ -0,0 +1,387 @@ +const fs = require('fs'); +const path = require('path'); + +const ROOT = process.cwd(); +const METHODS_DIR = path.join(ROOT, 'methods'); +const CHANGES_DIR = path.join(METHODS_DIR, 'changes'); + +function parseArgs(argv) { + const args = { + specPath: '', + dryRun: false, + docOnly: false, + help: false, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item === '--doc-only') { + args.docOnly = true; + continue; + } + + if (item === '--help' || item === '-h') { + args.help = true; + continue; + } + + if (item.startsWith('--spec=')) { + const raw = String(item.slice('--spec='.length)).trim(); + args.specPath = raw ? path.resolve(ROOT, raw) : ''; + continue; + } + } + + if (!args.help && !args.specPath) { + throw new Error('Missing required --spec= argument.'); + } + + return args; +} + +function printHelp() { + console.log([ + 'Usage:', + ' npm run doc:api:update -- --spec=temp/api-doc-update.json', + ' npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run', + ' npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only', + '', + 'Options:', + ' --spec= Path to the fixed update spec JSON file.', + ' --dry-run Validate and print the planned changes without writing files.', + ' --doc-only Update methods/.json only and skip methods/changes/.json.', + ].join('\n')); +} + +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function assert(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +function readJsonFile(filePath) { + const raw = fs.readFileSync(filePath, 'utf8'); + return { + json: JSON.parse(raw), + indent: detectIndent(raw), + eol: detectEol(raw), + }; +} + +function detectIndent(raw) { + const match = raw.match(/^([ \t]+)"[^"]+":/m); + return match ? match[1] : ' '; +} + +function detectEol(raw) { + return raw.includes('\r\n') ? '\r\n' : '\n'; +} + +function writeJsonFile(filePath, value, indent, eol) { + const formatted = JSON.stringify(value, null, indent).replace(/\n/g, eol); + fs.writeFileSync(filePath, `${formatted}${eol}`, 'utf8'); +} + +function ensureString(value, fieldPath) { + assert(typeof value === 'string' && value.trim(), `${fieldPath} must be a non-empty string.`); +} + +function ensureBoolean(value, fieldPath) { + assert(typeof value === 'boolean', `${fieldPath} must be a boolean.`); +} + +function ensureArray(value, fieldPath) { + assert(Array.isArray(value), `${fieldPath} must be an array.`); +} + +function ensureStringArray(value, fieldPath) { + ensureArray(value, fieldPath); + value.forEach((item, index) => ensureString(item, `${fieldPath}[${index}]`)); +} + +function validateListOption(option, fieldPath) { + assert(isPlainObject(option), `${fieldPath} must be an object.`); + const hasValue = Object.prototype.hasOwnProperty.call(option, 'value'); + assert(hasValue, `${fieldPath}.value is required.`); +} + +function validateNamedField(field, fieldPath, allowSource) { + assert(isPlainObject(field), `${fieldPath} must be an object.`); + ensureString(field.name, `${fieldPath}.name`); + ensureString(field.type, `${fieldPath}.type`); + ensureBoolean(field.required, `${fieldPath}.required`); + ensureString(field.description, `${fieldPath}.description`); + + if (allowSource && Object.prototype.hasOwnProperty.call(field, 'source')) { + ensureString(field.source, `${fieldPath}.source`); + } + + if (Object.prototype.hasOwnProperty.call(field, 'list')) { + ensureArray(field.list, `${fieldPath}.list`); + field.list.forEach((item, index) => validateListOption(item, `${fieldPath}.list[${index}]`)); + } +} + +function validateErrorField(field, fieldPath) { + assert(isPlainObject(field), `${fieldPath} must be an object.`); + assert(Object.prototype.hasOwnProperty.call(field, 'code'), `${fieldPath}.code is required.`); + ensureString(field.message, `${fieldPath}.message`); +} + +function validateMethodDoc(methodDoc, fieldPath) { + assert(isPlainObject(methodDoc), `${fieldPath} must be an object.`); + ensureString(methodDoc.method, `${fieldPath}.method`); + ensureString(methodDoc.description, `${fieldPath}.description`); + ensureBoolean(methodDoc.isNeedAuth, `${fieldPath}.isNeedAuth`); + ensureBoolean(methodDoc.isNeedLogin, `${fieldPath}.isNeedLogin`); + ensureArray(methodDoc.headers, `${fieldPath}.headers`); + ensureArray(methodDoc.params, `${fieldPath}.params`); + ensureArray(methodDoc.response, `${fieldPath}.response`); + ensureArray(methodDoc.errors, `${fieldPath}.errors`); + + methodDoc.headers.forEach((item, index) => validateNamedField(item, `${fieldPath}.headers[${index}]`, false)); + methodDoc.params.forEach((item, index) => validateNamedField(item, `${fieldPath}.params[${index}]`, true)); + methodDoc.response.forEach((item, index) => validateNamedField(item, `${fieldPath}.response[${index}]`, false)); + methodDoc.errors.forEach((item, index) => validateErrorField(item, `${fieldPath}.errors[${index}]`)); +} + +function validateChange(change, fieldPath) { + assert(isPlainObject(change), `${fieldPath} must be an object.`); + ensureString(change.version, `${fieldPath}.version`); + ensureString(change.date, `${fieldPath}.date`); + ensureString(change.summary, `${fieldPath}.summary`); + ensureStringArray(change.methods, `${fieldPath}.methods`); + ensureStringArray(change.notes, `${fieldPath}.notes`); + + if (Object.prototype.hasOwnProperty.call(change, 'type')) { + ensureString(change.type, `${fieldPath}.type`); + } +} + +function validateCurrentDoc(doc, fieldPath) { + assert(isPlainObject(doc), `${fieldPath} must be an object.`); + assert(isPlainObject(doc.methods), `${fieldPath}.methods must be an object.`); + ensureArray(doc.methods.groups, `${fieldPath}.methods.groups`); +} + +function validateCurrentChanges(changes, fieldPath) { + ensureArray(changes, fieldPath); +} + +function validateSpec(spec, args) { + assert(isPlainObject(spec), 'Spec root must be an object.'); + ensureString(spec.docName, 'spec.docName'); + assert(/^[a-z0-9_-]+$/i.test(spec.docName), 'spec.docName must contain only letters, numbers, underscore, or dash.'); + + const docPath = path.join(METHODS_DIR, `${spec.docName}.json`); + const changePath = path.join(CHANGES_DIR, `${spec.docName}.json`); + + assert(fs.existsSync(docPath), `Target doc file not found: ${docPath}`); + if (!args.docOnly) { + assert(fs.existsSync(changePath), `Target change file not found: ${changePath}`); + } + + if (Object.prototype.hasOwnProperty.call(spec, 'docMeta')) { + assert(isPlainObject(spec.docMeta), 'spec.docMeta must be an object.'); + if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'updatedAt')) { + ensureString(spec.docMeta.updatedAt, 'spec.docMeta.updatedAt'); + } + if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'version')) { + ensureString(spec.docMeta.version, 'spec.docMeta.version'); + } + } + + assert(isPlainObject(spec.group), 'spec.group must be an object.'); + ensureString(spec.group.groupName, 'spec.group.groupName'); + ensureString(spec.group.module, 'spec.group.module'); + + ensureArray(spec.methods, 'spec.methods'); + assert(spec.methods.length > 0, 'spec.methods must contain at least one method doc.'); + const methodNames = new Set(); + spec.methods.forEach((item, index) => { + validateMethodDoc(item, `spec.methods[${index}]`); + assert(!methodNames.has(item.method), `Duplicate method in spec.methods: ${item.method}`); + methodNames.add(item.method); + }); + + if (!args.docOnly) { + validateChange(spec.change, 'spec.change'); + } else if (Object.prototype.hasOwnProperty.call(spec, 'change')) { + validateChange(spec.change, 'spec.change'); + } + + return { + docName: spec.docName, + docPath, + changePath, + docMeta: spec.docMeta || {}, + group: spec.group, + methods: spec.methods, + change: spec.change || null, + }; +} + +function findGroupIndex(groups, groupSpec) { + const byModule = groups.findIndex(group => group && group.module === groupSpec.module); + if (byModule >= 0) return byModule; + return groups.findIndex(group => group && group.groupName === groupSpec.groupName); +} + +function findMethodLocation(groups, methodName) { + for (let groupIndex = 0; groupIndex < groups.length; groupIndex += 1) { + const group = groups[groupIndex]; + const list = group && Array.isArray(group.list) ? group.list : []; + const methodIndex = list.findIndex(item => item && item.method === methodName); + if (methodIndex >= 0) { + return { groupIndex, methodIndex }; + } + } + return null; +} + +function cloneJson(value) { + return JSON.parse(JSON.stringify(value)); +} + +function applyDocUpdate(doc, groupSpec, methods, docMeta) { + const groups = doc.methods.groups; + let groupIndex = findGroupIndex(groups, groupSpec); + + if (groupIndex < 0) { + groups.push({ + groupName: groupSpec.groupName, + module: groupSpec.module, + list: [], + }); + groupIndex = groups.length - 1; + } + + const targetGroup = groups[groupIndex]; + targetGroup.groupName = groupSpec.groupName; + targetGroup.module = groupSpec.module; + if (!Array.isArray(targetGroup.list)) { + targetGroup.list = []; + } + + const summary = { + inserted: [], + updated: [], + moved: [], + }; + + for (const methodDoc of methods) { + const nextMethod = cloneJson(methodDoc); + const existingLocation = findMethodLocation(groups, methodDoc.method); + + if (!existingLocation) { + targetGroup.list.push(nextMethod); + summary.inserted.push(methodDoc.method); + continue; + } + + if (existingLocation.groupIndex === groupIndex) { + targetGroup.list[existingLocation.methodIndex] = nextMethod; + summary.updated.push(methodDoc.method); + continue; + } + + groups[existingLocation.groupIndex].list.splice(existingLocation.methodIndex, 1); + targetGroup.list.push(nextMethod); + summary.moved.push(methodDoc.method); + } + + if (docMeta.updatedAt) { + doc.updatedAt = docMeta.updatedAt; + } + + if (docMeta.version) { + doc.version = docMeta.version; + } + + return summary; +} + +function appendChange(changes, change) { + const exists = changes.some(item => item && item.version === change.version); + assert(!exists, `Duplicate change version detected: ${change.version}`); + changes.push(cloneJson(change)); +} + +function main() { + const args = parseArgs(process.argv.slice(2)); + if (args.help) { + printHelp(); + return; + } + + assert(fs.existsSync(args.specPath), `Spec file not found: ${args.specPath}`); + + const specRaw = fs.readFileSync(args.specPath, 'utf8'); + const spec = JSON.parse(specRaw); + const normalized = validateSpec(spec, args); + + const docState = readJsonFile(normalized.docPath); + validateCurrentDoc(docState.json, normalized.docPath); + + let changeState = null; + if (!args.docOnly) { + changeState = readJsonFile(normalized.changePath); + validateCurrentChanges(changeState.json, normalized.changePath); + } + + const docNext = cloneJson(docState.json); + const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta); + JSON.parse(JSON.stringify(docNext)); + + let changeNext = null; + if (!args.docOnly) { + changeNext = cloneJson(changeState.json); + appendChange(changeNext, normalized.change); + JSON.parse(JSON.stringify(changeNext)); + } + + console.log(`docName: ${normalized.docName}`); + console.log(`group: ${normalized.group.module} (${normalized.group.groupName})`); + console.log(`inserted: ${summary.inserted.length ? summary.inserted.join(', ') : '-'}`); + console.log(`updated: ${summary.updated.length ? summary.updated.join(', ') : '-'}`); + console.log(`moved: ${summary.moved.length ? summary.moved.join(', ') : '-'}`); + if (!args.docOnly && normalized.change) { + console.log(`change version: ${normalized.change.version}`); + } + + if (args.dryRun) { + console.log('dry-run: validated successfully, no files were written.'); + return; + } + + writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol); + console.log(`wrote: ${path.relative(ROOT, normalized.docPath)}`); + + if (!args.docOnly) { + writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol); + console.log(`wrote: ${path.relative(ROOT, normalized.changePath)}`); + } +} + +if (require.main === module) { + try { + main(); + } catch (error) { + console.error(error.message || error); + process.exitCode = 1; + } +} + +module.exports = { + applyDocUpdate, + parseArgs, + validateSpec, +}; \ No newline at end of file diff --git a/test/app/controller/docs.test.js b/test/app/controller/docs.test.js index e8d4a52..5897ab3 100644 --- a/test/app/controller/docs.test.js +++ b/test/app/controller/docs.test.js @@ -8,6 +8,47 @@ function hasSemanticKey(keys, candidates) { } describe('test/app/controller/docs.test.js', () => { + it('GET /docs should return an index page with docs file links', async () => { + const res = await app.httpRequest() + .get('/docs') + .expect('Content-Type', /html/) + .expect(200); + + assert.match(res.text, /docs 目录索引/); + assert.match(res.text, /]*data-window-href="\/docs\/order-workbench-list-api\.md"/i); + assert.doesNotMatch(res.text, /
  • \s*]*href="\/docs\/order-workbench-list-api\.md"/i); + }); + + it('GET /docs/order-workbench-list-api.md should return markdown content', async () => { + const res = await app.httpRequest() + .get('/docs/order-workbench-list-api.md') + .expect('Content-Type', /text\/markdown/) + .expect(200); + + assert.match(res.text, /^# 订单工作台 List 接口说明/m); + }); + + it('GET /docs should block path traversal attempts', async () => { + const res = await app.httpRequest() + .get('/docs/%2e%2e%2fapp.js') + .expect('Content-Type', /json/) + .expect(400); + + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /无效|越界|path/i); + }); + + it('GET /api/docs/system should still be available', async () => { + const res = await app.httpRequest() + .get('/api/docs/system') + .expect('Content-Type', /html/) + .expect(200); + + assert.match(res.text, /系统接口|API 文档/); + assert.match(res.text, /\/api\/docs\/system\/raw/); + assert.match(res.text, /]*data-window-href="\/api\/docs\/system\/raw"/i); + }); + it('GET /api/docs/system/changes should return 200 and a change-history JSON array', async () => { const res = await app.httpRequest() .get('/api/docs/system/changes') @@ -42,9 +83,9 @@ describe('test/app/controller/docs.test.js', () => { .expect(200); const html = res.text; - assert.match(html, /\/api\/docs\/system\/changes/, '页面中应提供 /api/docs/system/changes 入口'); + assert.match(html, /]*data-window-href="\/api\/docs\/system\/changes"/i, '页面中应提供 /api/docs/system/changes 的 window 入口'); assert.match(html, /查看变更记录|变更记录|changelog/i, '页面中应出现“查看变更记录”或同等入口文案'); - assert.match(html, /\/api\/docs\/system\/raw/, '页面中应提供 /api/docs/system/raw 入口'); + assert.match(html, /]*data-window-href="\/api\/docs\/system\/raw"/i, '页面中应提供 /api/docs/system/raw 的 window 入口'); assert.match(html, /查看\s*JSON|raw\s*json/i, '页面中应出现“查看 JSON”入口'); }); diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js index aee6931..9ef2e49 100644 --- a/test/app/controller/gateway.user.bindAccountByTempCode.test.js +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -7,14 +7,16 @@ const { invokeGatewayMethod, } = require('../../support/system_method_client'); -const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); +describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', function() { + let YE4S_TEST_USER_ID; -assert.ok( - Number.isInteger(YE4S_TEST_USER_ID) && YE4S_TEST_USER_ID > 0, - 'SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数' -); + before(function() { + YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); + if (!Number.isInteger(YE4S_TEST_USER_ID) || YE4S_TEST_USER_ID <= 0) { + this.skip(); + } + }); -describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => { it('should scan, bind, unbind, and bind again for ye4s user', async () => { const { token } = await getAuthToken(); diff --git a/test/app/controller/home.test.js b/test/app/controller/home.test.js index f178b9d..ae4657a 100644 --- a/test/app/controller/home.test.js +++ b/test/app/controller/home.test.js @@ -1,7 +1,9 @@ const { strict: assert } = require('node:assert'); const path = require('node:path'); const { statSync } = require('node:fs'); -const { app } = require('egg-mock/bootstrap'); +const { app, mm } = require('egg-mock/bootstrap'); +const HomeController = require('../../../app/controller/home'); +const PoloApiService = require('../../../app/service/systems/polo_api'); describe('test/app/controller/home.test.js', () => { it('should assert', async () => { @@ -20,4 +22,99 @@ describe('test/app/controller/home.test.js', () => { .expect('pong') .expect(200); }); + + it('should GET /testPoloApi return poloApi.test result directly', async () => { + const expectedResult = { + ok: true, + data: { + message: 'real result passthrough', + }, + }; + let callCount = 0; + + try { + mm(PoloApiService.prototype, 'test', async () => { + callCount += 1; + return expectedResult; + }); + + const res = await app.httpRequest() + .get('/testPoloApi') + .expect('Content-Type', /json/) + .expect(200); + + assert.deepEqual(res.body, expectedResult); + assert.equal(callCount, 1); + } finally { + mm.restore(); + } + }); + + it('should extract qimen warehouseCode from controller helper', async () => { + const controller = Object.create(HomeController.prototype); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + deliveryOrder: { + warehouseCode: '100000', + }, + }, + }), + '100000' + ); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + warehouseCode: 'warehouseCode', + deliveryOrder: { + warehouseCode: '100000', + }, + }, + }), + '100000' + ); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + warehouseCode: 'warehouseCode', + deliveryOrder: { + warehouseCode: 'warehouseCode', + }, + }, + }), + '' + ); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + deliveryOrder: { + warehouseCode: '', + }, + }, + }), + '' + ); + }); + + it('should ignore unrelated string nodes when extracting qimen warehouseCode', async () => { + const controller = Object.create(HomeController.prototype); + + assert.equal( + controller.getQimenWarehouseCode({ + request: { + deliveryOrder: { + warehouseCode: 'warehouseCode', + orderStatus: '100000', + note: '真实请求里不应被这些字符串节点误命中', + }, + traceId: '100000', + }, + }), + '' + ); + }); }); diff --git a/test/app/controller/qimen.deliveryorder.reviewFlow.test.js b/test/app/controller/qimen.deliveryorder.reviewFlow.test.js new file mode 100644 index 0000000..4cda5da --- /dev/null +++ b/test/app/controller/qimen.deliveryorder.reviewFlow.test.js @@ -0,0 +1,432 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { + getAuthToken, + invokeSystemMethod, + invokeQimenMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FIXED_RELATION = { + storeId: 1000000, + warehouseId: 100000, +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +/** + * 将字符串转义为 XML 安全文本。 + * @param {string|number|null|undefined} value 待转义值。 + * @return {string} 转义后的 XML 文本。 + */ +function escapeXml(value) { + return String(value === null || value === undefined ? '' : value).replace(/[<>&'\"]/g, character => { + switch (character) { + case '<': + return '<'; + case '>': + return '>'; + case '&': + return '&'; + case '\'': + return '''; + case '"': + return '"'; + default: + return character; + } + }); +} + +/** + * 从候选列表中挑选固定测试签约关系。 + * @param {Array} relations 签约关系列表。 + * @return {object|null} 固定测试关系。 + */ +function pickFixedTestRelation(relations) { + if (!Array.isArray(relations)) { + return null; + } + + return relations.find(item => Number(item.store_id) === FIXED_RELATION.storeId + && Number(item.warehouse_id) === FIXED_RELATION.warehouseId) || null; +} + +/** + * 从接口配置列表中挑选一个已启用的 QM_WMS 配置。 + * @param {Array} configs 接口配置列表。 + * @return {object|null} 可用奇门配置。 + */ +function pickEnabledQimenConfig(configs) { + if (!Array.isArray(configs)) { + return null; + } + + return configs.find(item => Number(item.is_enabled) === 1 + && (item.interface_category === 'QM_WMS' || item.interface_type?.interface_category === 'QM_WMS')) || null; +} + +/** + * 从库存搜索结果中挑选一个可用 SKU。 + * @param {Array} stocks 库存搜索结果。 + * @return {object|null} 可用 SKU。 + */ +function pickUsableStock(stocks) { + if (!Array.isArray(stocks)) { + return null; + } + + const resolveAvailableQuantity = item => { + const directAvailableFields = [ + item?.available_quantity, + item?.availableQuantity, + item?.available, + ]; + + for (const value of directAvailableFields) { + const numeric = Number(value); + if (Number.isFinite(numeric) && numeric > 0) { + return numeric; + } + } + + const quantity = Number(item?.quantity); + const lockedQuantity = Number(item?.locked_quantity ?? item?.lockedQuantity ?? item?.lockQuantity); + if (Number.isFinite(quantity) && quantity > 0) { + const resolvedLocked = Number.isFinite(lockedQuantity) ? lockedQuantity : 0; + return Math.max(0, quantity - resolvedLocked); + } + + const storageList = Array.isArray(item?.storage) ? item.storage : []; + for (const storageItem of storageList) { + const storageAvailable = Number(storageItem?.available_quantity ?? storageItem?.availableQuantity ?? storageItem?.available); + if (Number.isFinite(storageAvailable) && storageAvailable > 0) { + return storageAvailable; + } + + const storageQuantity = Number(storageItem?.quantity); + const storageLocked = Number(storageItem?.locked_quantity ?? storageItem?.lockedQuantity); + if (Number.isFinite(storageQuantity) && storageQuantity > 0) { + const resolvedStorageLocked = Number.isFinite(storageLocked) ? storageLocked : 0; + const available = Math.max(0, storageQuantity - resolvedStorageLocked); + if (available > 0) { + return available; + } + } + } + + return 0; + }; + + return stocks.find(item => resolveAvailableQuantity(item) > 0) || null; +} + +/** + * 构建待审核订单的 XML 请求体。 + * @param {Object} payload 请求参数。 + * @return {string} XML 请求体。 + */ +function buildDeliveryOrderXml(payload) { + const { deliveryOrderCode, warehouseCode, stock, planQty, orderType, receiverInfo } = payload; + + return ` + + + ${escapeXml(deliveryOrderCode)} + TAOBAO + 淘宝 + ${escapeXml(warehouseCode)} + ${escapeXml(orderType)} + + ${escapeXml(receiverInfo.name)} + ${escapeXml(receiverInfo.mobile)} + ${escapeXml(receiverInfo.province)} + ${escapeXml(receiverInfo.city)} + ${escapeXml(receiverInfo.area)} + ${escapeXml(receiverInfo.town)} + ${escapeXml(receiverInfo.detailAddress)} + ${escapeXml(receiverInfo.zipCode)} + + + + + ${escapeXml(stock.id)} + ${escapeXml(stock.item_code)} + ${escapeXml(stock.item_name)} + ${escapeXml(planQty)} + 1 + + +`; +} + +/** + * 切换到可访问仓库订单和库存接口的仓库角色。 + * @param {string} token 当前登录 token。 + * @return {Promise<{token: string, roleId: number}|null>} 切换结果。 + */ +async function switchToWarehouseRole(token) { + const infoRes = await invokeSystemMethod('user.info', {}, token, EXTRA_HEADERS); + + assert.equal(infoRes.status, 200, `user.info HTTP 状态异常: ${JSON.stringify(infoRes.body)}`); + assert.equal(infoRes.body.flag, 'success', `user.info 返回失败: ${JSON.stringify(infoRes.body)}`); + assert.equal(infoRes.body.code, 200, `user.info code 异常: ${JSON.stringify(infoRes.body)}`); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const candidateRoleIds = [ + ...new Set([ + ...employees + .filter(item => item && item.role_type === 'warehouse' && Number(item.id)) + .map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)), + ]; + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, token, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || Number(changeRes.body?.code) !== 200) { + continue; + } + + const switchedToken = changeRes.body?.data?.token || token; + + const relationProbeRes = await invokeSystemMethod('storeWarehouse.store.list', { + page: 1, + page_size: 50, + }, switchedToken, EXTRA_HEADERS); + + const stockProbeRes = await invokeSystemMethod('stock.warehouse.search', { + keyword: '', + store_id: FIXED_RELATION.storeId, + with_stock: true, + is_batch: false, + }, switchedToken, EXTRA_HEADERS); + + if (relationProbeRes.status === 200 + && relationProbeRes.body?.flag === 'success' + && Number(relationProbeRes.body?.code) === 200 + && pickFixedTestRelation(relationProbeRes.body?.data?.list) + && stockProbeRes.status === 200 + && stockProbeRes.body?.flag === 'success' + && Number(stockProbeRes.body?.code) === 200) { + return { + token: switchedToken, + roleId, + }; + } + } + + return null; +} + +describe('test/app/controller/qimen.deliveryorder.reviewFlow.test.js', () => { + it('should create, review and move a delivery order through the real qimen flow', async function() { + const auth = await getAuthToken({ forceLogin: true }); + const switched = await switchToWarehouseRole(auth.token); + + if (!switched) { + this.skip(); + return; + } + + let relation = null; + let qimenConfig = null; + let stock = null; + let originalPolicyConfig = null; + let contractId = null; + const deliveryOrderCode = `QIMEN_REVIEW_${Date.now()}_${crypto.randomBytes(4).toString('hex').toUpperCase()}`; + + try { + const relationListRes = await invokeSystemMethod('storeWarehouse.store.list', { + page: 1, + page_size: 50, + }, switched.token, EXTRA_HEADERS); + + assert.equal(relationListRes.status, 200, `查询签约关系列表 HTTP 状态异常: ${JSON.stringify(relationListRes.body)}`); + assert.equal(relationListRes.body.flag, 'success', `查询签约关系列表失败: ${JSON.stringify(relationListRes.body)}`); + assert.equal(Number(relationListRes.body.code), 200, `查询签约关系列表 code 异常: ${JSON.stringify(relationListRes.body)}`); + + relation = pickFixedTestRelation(relationListRes.body?.data?.list); + if (!relation) { + this.skip(); + return; + } + + contractId = Number(relation.id || 0); + originalPolicyConfig = relation.policy_config && typeof relation.policy_config === 'object' + ? { ...relation.policy_config } + : null; + + if (!originalPolicyConfig) { + this.skip(); + return; + } + + const apiConfigRes = await invokeSystemMethod('storeWarehouse.store.listApiConfig', { + id: contractId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(apiConfigRes.status, 200, `查询接口配置列表 HTTP 状态异常: ${JSON.stringify(apiConfigRes.body)}`); + assert.equal(apiConfigRes.body.flag, 'success', `查询接口配置列表失败: ${JSON.stringify(apiConfigRes.body)}`); + assert.equal(Number(apiConfigRes.body.code), 200, `查询接口配置列表 code 异常: ${JSON.stringify(apiConfigRes.body)}`); + + qimenConfig = pickEnabledQimenConfig(apiConfigRes.body?.data?.list); + if (!qimenConfig + || !String(qimenConfig.qimen_app_key || '').trim() + || !String(qimenConfig.qimen_customer_id || '').trim() + || !String(qimenConfig.qimen_warehouse_code || '').trim()) { + this.skip(); + return; + } + + const stockSearchRes = await invokeSystemMethod('stock.warehouse.search', { + keyword: '', + store_id: FIXED_RELATION.storeId, + with_stock: true, + is_batch: false, + }, switched.token, EXTRA_HEADERS); + + assert.equal(stockSearchRes.status, 200, `查询库存搜索 HTTP 状态异常: ${JSON.stringify(stockSearchRes.body)}`); + assert.equal(stockSearchRes.body.flag, 'success', `查询库存搜索失败: ${JSON.stringify(stockSearchRes.body)}`); + assert.equal(Number(stockSearchRes.body.code), 200, `查询库存搜索 code 异常: ${JSON.stringify(stockSearchRes.body)}`); + + stock = pickUsableStock(stockSearchRes.body?.data?.data || stockSearchRes.body?.data?.list || []); + if (!stock) { + this.skip(); + return; + } + + const nextPolicyConfig = { + ...originalPolicyConfig, + need_order_approval: 1, + }; + + const savePolicyRes = await invokeSystemMethod('storeWarehouse.store.savePolicyConfig', { + id: contractId, + policy_config: nextPolicyConfig, + }, switched.token, EXTRA_HEADERS); + + assert.equal(savePolicyRes.status, 200, `临时设置审核策略 HTTP 状态异常: ${JSON.stringify(savePolicyRes.body)}`); + assert.equal(savePolicyRes.body.flag, 'success', `临时设置审核策略失败: ${JSON.stringify(savePolicyRes.body)}`); + assert.equal(Number(savePolicyRes.body.code), 200, `临时设置审核策略 code 异常: ${JSON.stringify(savePolicyRes.body)}`); + assert.equal(Number(savePolicyRes.body?.data?.policy_config?.need_order_approval || 0), 1, '临时策略必须把 need_order_approval 置为 1'); + + const receiverInfo = { + name: '自动化测试收件人', + mobile: '13800138000', + province: '广东省', + city: '广州市', + area: '黄埔区', + town: '知识城街道', + detailAddress: `自动化测试地址 ${deliveryOrderCode}`, + zipCode: '510000', + }; + const requestXml = buildDeliveryOrderXml({ + deliveryOrderCode, + warehouseCode: String(qimenConfig.qimen_warehouse_code || '').trim(), + stock, + planQty: 1, + orderType: 'JYCK', + receiverInfo, + }); + + const createRes = await invokeQimenMethod('deliveryorder.create', requestXml, { + appKey: String(qimenConfig.qimen_app_key || '').trim(), + customerId: String(qimenConfig.qimen_customer_id || '').trim(), + contentType: 'application/xml', + format: 'xml', + signMethod: 'md5', + }); + + assert.equal(createRes.status, 200, `qimen 创建待审核订单 HTTP 状态异常: ${createRes.body}`); + const createResponse = createRes.parsed?.response || createRes.parsed || {}; + assert.equal(String(createResponse.flag || ''), 'success', `qimen 创建待审核订单失败。请求 XML:\n${requestXml}\n响应原文:\n${createRes.body}`); + assert.match(String(createRes.body || ''), /deliveryOrderId|createTime|success/i, `qimen 创建响应缺少预期字段。请求 XML:\n${requestXml}\n响应原文:\n${createRes.body}`); + + const reviewListRes = await invokeSystemMethod('order.reviewOrder.list', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + delivery_order_code: deliveryOrderCode, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewListRes.status, 200, `待审核列表 HTTP 状态异常: ${JSON.stringify(reviewListRes.body)}`); + assert.equal(reviewListRes.body.flag, 'success', `待审核列表查询失败: ${JSON.stringify(reviewListRes.body)}`); + assert.equal(Number(reviewListRes.body.code), 200, `待审核列表 code 异常: ${JSON.stringify(reviewListRes.body)}`); + + const reviewItems = Array.isArray(reviewListRes.body?.data?.list) ? reviewListRes.body.data.list : []; + const createdReviewOrder = reviewItems.find(item => String(item.delivery_order_code) === deliveryOrderCode); + assert.ok(createdReviewOrder, `待审核列表未命中刚创建的订单。响应原文: ${JSON.stringify(reviewListRes.body)}`); + assert.equal(Number(createdReviewOrder.step), 0, `新建订单应处于待审核 step=0。响应原文: ${JSON.stringify(reviewListRes.body)}`); + + const reviewActionRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { + ids: [ Number(createdReviewOrder.id) ], + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewActionRes.status, 200, `审核接口 HTTP 状态异常: ${JSON.stringify(reviewActionRes.body)}`); + assert.equal(reviewActionRes.body.flag, 'success', `审核接口调用失败: ${JSON.stringify(reviewActionRes.body)}`); + assert.equal(Number(reviewActionRes.body.code), 200, `审核接口 code 异常: ${JSON.stringify(reviewActionRes.body)}`); + assert.equal(Number(reviewActionRes.body?.data?.step), 1, `审核后订单 step 应变为 1。响应原文: ${JSON.stringify(reviewActionRes.body)}`); + + const pendingListRes = await invokeSystemMethod('order.pendingOrder.list', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + delivery_order_code: deliveryOrderCode, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(pendingListRes.status, 200, `待处理列表 HTTP 状态异常: ${JSON.stringify(pendingListRes.body)}`); + assert.equal(pendingListRes.body.flag, 'success', `待处理列表查询失败: ${JSON.stringify(pendingListRes.body)}`); + assert.equal(Number(pendingListRes.body.code), 200, `待处理列表 code 异常: ${JSON.stringify(pendingListRes.body)}`); + + const pendingItems = Array.isArray(pendingListRes.body?.data?.list) ? pendingListRes.body.data.list : []; + const pendingOrder = pendingItems.find(item => String(item.delivery_order_code) === deliveryOrderCode); + assert.ok(pendingOrder, `待处理列表未命中已审核订单。响应原文: ${JSON.stringify(pendingListRes.body)}`); + assert.ok([ 1, 2 ].includes(Number(pendingOrder.step)), `审核后订单 step 应处于待处理范围。响应原文: ${JSON.stringify(pendingListRes.body)}`); + + const reviewAfterRes = await invokeSystemMethod('order.reviewOrder.list', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + delivery_order_code: deliveryOrderCode, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(reviewAfterRes.status, 200, `复查待审核列表 HTTP 状态异常: ${JSON.stringify(reviewAfterRes.body)}`); + assert.equal(reviewAfterRes.body.flag, 'success', `复查待审核列表失败: ${JSON.stringify(reviewAfterRes.body)}`); + assert.equal(Number(reviewAfterRes.body.code), 200, `复查待审核列表 code 异常: ${JSON.stringify(reviewAfterRes.body)}`); + + const reviewAfterItems = Array.isArray(reviewAfterRes.body?.data?.list) ? reviewAfterRes.body.data.list : []; + const reviewAfterOrder = reviewAfterItems.find(item => String(item.delivery_order_code) === deliveryOrderCode); + assert.equal(reviewAfterOrder, undefined, `审核完成后不应再命中待审核列表。响应原文: ${JSON.stringify(reviewAfterRes.body)}`); + } finally { + if (contractId && originalPolicyConfig) { + const restoreRes = await invokeSystemMethod('storeWarehouse.store.savePolicyConfig', { + id: contractId, + policy_config: originalPolicyConfig, + }, switched.token, EXTRA_HEADERS); + + assert.equal(restoreRes.status, 200, `恢复原 policy_config 的 HTTP 状态异常: ${JSON.stringify(restoreRes.body)}`); + assert.equal(restoreRes.body.flag, 'success', `恢复原 policy_config 失败: ${JSON.stringify(restoreRes.body)}`); + assert.equal(Number(restoreRes.body.code), 200, `恢复原 policy_config code 异常: ${JSON.stringify(restoreRes.body)}`); + } + } + }); +}); diff --git a/test/app/controller/system.order.badgeCount.test.js b/test/app/controller/system.order.badgeCount.test.js new file mode 100644 index 0000000..340787a --- /dev/null +++ b/test/app/controller/system.order.badgeCount.test.js @@ -0,0 +1,172 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../support/order_service_test_helper'); + +function createBadgeCountHarness(rowsByModule = {}) { + const { service, captures } = createOrderHarness(OrderIndexService, { + rowsByModule, + }); + const cacheStore = new Map(); + const cacheStats = { + getCalls: 0, + setCalls: 0, + }; + + service.app.getCacheAsync = async cacheKey => { + cacheStats.getCalls += 1; + + if (!cacheStore.has(cacheKey)) { + return null; + } + + return cacheStore.get(cacheKey); + }; + + service.app.setCacheAsync = async (cacheKey, value) => { + cacheStats.setCalls += 1; + cacheStore.set(cacheKey, value); + }; + + return { + service, + captures, + cacheStats, + }; +} + +describe('test/app/controller/system.order.badgeCount.test.js', () => { + it('should return 8 badge fields and keep delivery/archive as 99+', async () => { + const { service, captures } = createBadgeCountHarness({ + reviewOrder: buildRows(99, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + pendingOrder: buildRows(100, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + outboundOrder: buildRows(1, () => ({ + step: 1, + outbound_status: 'padding', + dispatch_lane: 'm4', + })), + expectionOrder: buildRows(2, () => ({ + step: 3, + dispatch_lane: 'm4', + })), + entrustOrder: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }); + + const result = await service.badgeCount(); + + assert.deepEqual(Object.keys(result), [ + 'reviewOrder', + 'pendingOrder', + 'outboundOrder', + 'expectionOrder', + 'entrustOrder', + 'deliveryOrder', + 'deliveryExpectionOrder', + 'archiveOrder', + ]); + assert.equal(result.reviewOrder, 99); + assert.equal(result.pendingOrder, '99+'); + assert.equal(result.outboundOrder, 1); + assert.equal(result.expectionOrder, 2); + assert.equal(result.entrustOrder, 1); + assert.equal(result.deliveryOrder, '99+'); + assert.equal(result.deliveryExpectionOrder, '99+'); + assert.equal(result.archiveOrder, '99+'); + + assert.deepEqual(captures.map(item => item.moduleName), [ + 'reviewOrder', + 'pendingOrder', + 'outboundOrder', + 'expectionOrder', + 'entrustOrder', + ]); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 0 }, captures[0].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 1, outbound_status: 'none' }, captures[1].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 1, outbound_status: 'padding' }, captures[2].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000, step: 3 }, captures[3].countWhere)); + assert.ok(matchesWhere({ warehouse_id: 100000 }, captures[4].countWhere)); + }); + + it('should use cache and avoid repeated count queries', async () => { + const { service, captures, cacheStats } = createBadgeCountHarness({ + reviewOrder: buildRows(2, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + pendingOrder: buildRows(2, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + outboundOrder: buildRows(2, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + expectionOrder: buildRows(1, () => ({ + step: 3, + dispatch_lane: 'm4', + })), + entrustOrder: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }); + + const firstResult = await service.badgeCount(); + const firstCaptureCount = captures.length; + + const secondResult = await service.badgeCount(); + + assert.deepEqual(secondResult, firstResult); + assert.equal(captures.length, firstCaptureCount); + assert.equal(cacheStats.setCalls, 1); + assert.equal(cacheStats.getCalls, 2); + }); + + it('should keep exact counts within 99 and convert larger counts to 99+', async () => { + const { service } = createBadgeCountHarness({ + reviewOrder: buildRows(1, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + pendingOrder: buildRows(100, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + outboundOrder: buildRows(99, () => ({ + step: 1, + outbound_status: 'none', + dispatch_lane: 'm4', + })), + expectionOrder: buildRows(3, () => ({ + step: 3, + dispatch_lane: 'm4', + })), + entrustOrder: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }); + + const result = await service.badgeCount(); + + assert.equal(result.reviewOrder, 1); + assert.equal(result.pendingOrder, '99+'); + assert.equal(result.outboundOrder, 99); + assert.equal(result.expectionOrder, 3); + assert.equal(result.entrustOrder, 1); + }); +}); diff --git a/test/app/controller/system.order.getreviewOrderlist.test.js b/test/app/controller/system.order.getreviewOrderlist.test.js index 82303fb..f8fe10f 100644 --- a/test/app/controller/system.order.getreviewOrderlist.test.js +++ b/test/app/controller/system.order.getreviewOrderlist.test.js @@ -1,83 +1,33 @@ 'use strict'; const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('../../support/system_method_client'); +const ReviewOrderService = require('../../../app/service/systemMethods/order/reviewOrder'); +const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper'); -const EXTRA_HEADERS = { - platform: 'web', - project: 'all', -}; +describe('test/app/controller/system.order.reviewOrder.list.test.js', () => { + it('should return list/pagination for reviewOrder.list', async () => { + const { service, captures } = createOrderHarness(ReviewOrderService, { + rowsByModule: { + reviewOrder: buildRows(1, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + }, + }); -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; - -async function switchToWarehouseRoleWithOrderData(token) { - let currentToken = token; - const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); - assert.equal(infoRes.status, 200); - assert.equal(infoRes.body.flag, 'success'); - assert.equal(infoRes.body.code, 200); - - const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; - - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); - - for (const roleId of candidateRoleIds) { - const changeRes = await invokeSystemMethod('user.changeRole', { - roleId, - }, currentToken, EXTRA_HEADERS); - - if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { - continue; - } - - currentToken = changeRes.body?.data?.token || currentToken; - - const statsRes = await invokeSystemMethod('order.stats', { - where: {}, - }, currentToken, EXTRA_HEADERS); - - assert.equal(statsRes.status, 200); - assert.equal(statsRes.body.flag, 'success'); - assert.equal(statsRes.body.code, 200); - - const total = Number(statsRes.body?.data?.total || 0); - if (total > 0) { - return { - token: currentToken, - }; - } - } - - throw new Error('未找到有订单数据的仓库角色'); -} - -describe('test/app/controller/system.order.getreviewOrderlist.test.js', () => { - it('should call order.getreviewOrderlist with platform=web project=all', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); - - const res = await invokeSystemMethod('order.getreviewOrderlist', { + const result = await service.list({ pagination: { page: 1, - pageSize: 10, + pageSize: 1, }, where: {}, - }, switched.token, EXTRA_HEADERS); + }); - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - assert.ok(res.body.data); - assert.ok(Array.isArray(res.body.data.list)); - assert.ok(res.body.data.pagination); - assert.equal(typeof res.body.data.pagination.total, 'number'); + assert.equal(captures[0].moduleName, 'reviewOrder'); + assert.ok(Array.isArray(result.list)); + assert.ok(result.pagination); + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 1); + assert.equal(result.list.length, 1); }); }); diff --git a/test/app/controller/system.order.namespaced.test.js b/test/app/controller/system.order.namespaced.test.js index dfb14a9..63bd0aa 100644 --- a/test/app/controller/system.order.namespaced.test.js +++ b/test/app/controller/system.order.namespaced.test.js @@ -1,198 +1,64 @@ 'use strict'; const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('../../support/system_method_client'); - -const EXTRA_HEADERS = { - platform: 'web', - project: 'all', -}; - -const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; - -function mapReviewStatusToStep(reviewStatus) { - const status = String(reviewStatus || 'none').trim(); - if (status === 'fin') { - return 1; - } - if (status === 'running' || status === 'padding') { - return 2; - } - if (status === 'error') { - return 3; - } - return 0; -} - -async function switchToWarehouseRoleWithOrderData(token) { - let currentToken = token; - const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); - assert.equal(infoRes.status, 200); - assert.equal(infoRes.body.flag, 'success'); - assert.equal(infoRes.body.code, 200); - - const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; - - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); - - for (const roleId of candidateRoleIds) { - const changeRes = await invokeSystemMethod('user.changeRole', { - roleId, - }, currentToken, EXTRA_HEADERS); - - if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { - continue; - } - - currentToken = changeRes.body?.data?.token || currentToken; - - const statsRes = await invokeSystemMethod('order.stats', { - where: {}, - }, currentToken, EXTRA_HEADERS); - - assert.equal(statsRes.status, 200); - assert.equal(statsRes.body.flag, 'success'); - assert.equal(statsRes.body.code, 200); - - const total = Number(statsRes.body?.data?.total || 0); - if (total > 0) { - return { - token: currentToken, - roleId, - total, - }; - } - } - - throw new Error('未找到有订单数据的仓库角色'); -} +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); +const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper'); describe('test/app/controller/system.order.namespaced.test.js', () => { - it('should query all namespaced order lists', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); + it('should return list/pagination for order.list', async () => { + const { service, captures } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }, + }); - const methods = [ - 'order.reviewOrder.getreviewOrderlist', - 'order.deliveryOrder.getdeliveryOrderlist', - 'order.pendingOrder.getpendingOrderlist', - 'order.expectionOrder.getexpectionOrderlist', - 'order.archiveOrder.getarchiveOrderlist', - ]; - - for (const method of methods) { - const res = await invokeSystemMethod(method, { - pagination: { - page: 1, - pageSize: 10, - }, - where: {}, - }, switched.token, EXTRA_HEADERS); - - assert.equal(res.status, 200, `${method} http status 异常`); - assert.equal(res.body.flag, 'success', `${method} flag 异常`); - assert.equal(res.body.code, 200, `${method} code 异常`); - assert.ok(res.body.data, `${method} 缺少 data`); - assert.ok(Array.isArray(res.body.data.list), `${method} list 不是数组`); - assert.ok(res.body.data.pagination, `${method} 缺少 pagination`); - assert.equal(typeof res.body.data.pagination.total, 'number', `${method} total 不是 number`); - } - }); - - it('should review order through namespaced method and restore status', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); - - const listRes = await invokeSystemMethod('order.list', { + const result = await service.list({ pagination: { page: 1, pageSize: 1, }, - where: {}, - }, switched.token, EXTRA_HEADERS); + where: { + step: 1, + }, + }); - assert.equal(listRes.status, 200); - assert.equal(listRes.body.flag, 'success'); - assert.equal(listRes.body.code, 200); + const capture = captures[0]; - const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null; - assert.ok(order, '订单列表为空,无法测试目录化 reviewOrder'); - assert.ok(order.id, '订单缺少 id,无法测试目录化 reviewOrder'); - - const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || '')) - ? String(order.inspection_status) - : 'none'; - const targetStatus = originalStatus === 'fin' ? 'running' : 'fin'; - - const reviewRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { - id: Number(order.id), - review_status: targetStatus, - }, switched.token, EXTRA_HEADERS); - - assert.equal(reviewRes.status, 200); - assert.equal(reviewRes.body.flag, 'success'); - assert.equal(reviewRes.body.code, 200); - assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id)); - assert.equal(reviewRes.body?.data?.inspection_status, targetStatus); - assert.equal(Number(reviewRes.body?.data?.step), mapReviewStatusToStep(targetStatus)); - - const restoreRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', { - id: Number(order.id), - review_status: originalStatus, - }, switched.token, EXTRA_HEADERS); - - assert.equal(restoreRes.status, 200); - assert.equal(restoreRes.body.flag, 'success'); - assert.equal(restoreRes.body.code, 200); - assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); - assert.equal(Number(restoreRes.body?.data?.step), mapReviewStatusToStep(originalStatus)); + assert.equal(capture.moduleName, 'order'); + assert.equal(result.pagination.pageSize, 1); + assert.equal(result.list.length, 1); }); - it('should return step in delivery orders and support filtering', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); + it('should hide deprecated order compatibility aliases', async () => { + const { service } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }, + }); - const listRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', { - pagination: { page: 1, pageSize: 10 }, - where: {}, - }, switched.token, EXTRA_HEADERS); + const deprecatedMethods = [ + 'reviewOrder', + 'pendingOrder', + 'outboundOrder', + 'expectionOrder', + 'entrustOrder', + 'deliveryOrder', + 'deliveryExpectionOrder', + 'archiveOrder', + ]; - assert.equal(listRes.status, 200); - assert.equal(listRes.body.flag, 'success'); - assert.equal(listRes.body.code, 200); - - const orders = listRes.body?.data?.list; - assert.ok(Array.isArray(orders)); - - if (orders.length > 0) { - assert.ok(Object.prototype.hasOwnProperty.call(orders[0], 'step'), '发货单应包含 step 字段'); - const sampleStep = Number(orders[0].step); - - const filteredRes = await invokeSystemMethod('order.deliveryOrder.getdeliveryOrderlist', { - pagination: { page: 1, pageSize: 10 }, - where: { step: sampleStep }, - }, switched.token, EXTRA_HEADERS); - - assert.equal(filteredRes.status, 200); - assert.equal(filteredRes.body.flag, 'success'); - assert.equal(filteredRes.body.code, 200); - const filteredOrders = filteredRes.body?.data?.list; - assert.ok(Array.isArray(filteredOrders)); - if (filteredOrders.length > 0) { - assert.ok( - filteredOrders.every(order => Number(order.step) === sampleStep), - `按 step=${sampleStep} 过滤后,所有订单都应是该状态` - ); - } + for (const methodName of deprecatedMethods) { + assert.equal(typeof service[methodName], 'undefined', `${methodName} 仍被暴露`); } + + assert.equal(typeof service.list, 'function'); + assert.equal(typeof service.badgeCount, 'function'); + assert.equal(typeof service.manualOutboundOrder, 'function'); }); }); diff --git a/test/app/controller/system.order.outbound.exposure.test.js b/test/app/controller/system.order.outbound.exposure.test.js new file mode 100644 index 0000000..3b0b40b --- /dev/null +++ b/test/app/controller/system.order.outbound.exposure.test.js @@ -0,0 +1,90 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); +const { buildRows, createOrderHarness } = require('../../support/order_service_test_helper'); + +describe('test/app/controller/system.order.outbound.exposure.test.js', () => { + it('should keep manualOutboundOrder exposed and remove deprecated outboundOrder alias', async () => { + const { service } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1, () => ({ + step: 1, + dispatch_lane: 'm4', + })), + }, + }); + + const methodNames = [ + 'markOutboundOrder', + 'manualOutboundOrder', + ]; + + assert.equal(typeof service.markOutboundOrder, 'undefined'); + assert.equal(typeof service.outboundOrder, 'undefined'); + assert.equal(typeof service.manualOutboundOrder, 'function'); + + const methodsManifest = require('../../../methods/system.json'); + const exposedMethodNames = methodsManifest.methods.groups + .flatMap(group => (Array.isArray(group.list) ? group.list : [])) + .map(item => item.method); + + const hasInternalOutboundMethod = exposedMethodNames.some(methodName => { + return methodName === 'order.markOutboundOrder'; + }); + + const hasDeprecatedOutboundAlias = exposedMethodNames.some(methodName => { + return methodName === 'order.outboundOrder'; + }); + + assert.equal(hasInternalOutboundMethod, false); + assert.equal(hasDeprecatedOutboundAlias, false); + + for (const methodName of methodNames) { + if (methodName === 'markOutboundOrder') { + continue; + } + + assert.equal(typeof service[methodName], 'function'); + } + }); + + it('should pass batch params through manualOutboundOrder to orderDeliveryMigration and return its result', async () => { + const { ctx, service } = createOrderHarness(OrderIndexService, { + rowsByModule: { + order: buildRows(1), + }, + }); + + const requestData = { + warehouseId: 100000, + warehouseIds: [ 100000, 100001 ], + queryTimeoutMs: 12345, + executionTimeoutMs: 23456, + batchSize: 20, + customFlag: 'keep-as-is', + }; + + const expectedResult = { + ok: true, + totalCreated: 8, + }; + + let receivedPayload = null; + ctx.service = { + systems: { + orderDeliveryMigration: { + async syncOutboundOrdersToDelivery(data) { + receivedPayload = data; + return expectedResult; + }, + }, + }, + }; + + const result = await service.manualOutboundOrder(requestData); + + assert.strictEqual(receivedPayload, requestData); + assert.deepEqual(result, expectedResult); + }); +}); diff --git a/test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js b/test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js new file mode 100644 index 0000000..ca0f4b6 --- /dev/null +++ b/test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js @@ -0,0 +1,613 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const PendingOrderService = require('../../../app/service/systemMethods/order/pendingOrder'); +const ReviewOrderService = require('../../../app/service/systemMethods/order/reviewOrder'); +const ExpectionOrderService = require('../../../app/service/systemMethods/order/expectionOrder'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../support/order_service_test_helper'); +const OrderIndexService = require('../../../app/service/systemMethods/order/index'); + +/** + * 创建支持更新结果回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + capture.rows = storedRows; + + return { + async count(options = {}) { + capture.countWhere = options.where; + return storedRows.filter(row => matchesWhere(row, options.where)).length; + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; +} + +/** + * 创建待处理订单反审服务测试实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ service: PendingOrderService, capture: Object }} 服务与调用记录。 + */ +function createPendingOrderService(rows) { + const { service } = createOrderHarness(PendingOrderService, { + defaultRows: rows, + }); + const capture = {}; + const model = createMutableOrderModel(rows, capture); + + service.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + return { + service, + capture, + }; +} + +/** + * 创建待处理订单取消与列表语义验证的共享服务实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ pendingService: PendingOrderService, orderService: OrderIndexService, reviewService: ReviewOrderService, expectionService: ExpectionOrderService, capture: Object }} 共享服务与调用记录。 + */ +function createPendingOrderWorkflowService(rows) { + const { ctx, service: pendingService } = createOrderHarness(PendingOrderService, { + defaultRows: rows, + }); + const orderService = new OrderIndexService(ctx); + const reviewService = new ReviewOrderService(ctx); + const expectionService = new ExpectionOrderService(ctx); + const capture = {}; + const model = createMutableOrderModel(rows, capture); + + pendingService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + orderService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + reviewService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + expectionService.getOrderModel = async moduleName => { + capture.moduleName = moduleName; + return model; + }; + + return { + pendingService, + orderService, + reviewService, + expectionService, + capture, + }; +} + +describe('test/app/controller/system.order.pendingOrder.reverseReviewOrder.test.js', () => { + it('should reverse batch orders by ids array', async () => { + const { service, capture } = createPendingOrderService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.reverseReviewOrder({ + ids: [ 1, 3 ], + }); + + assert.equal(capture.updateValues.inspection_status, 'none'); + assert.equal(capture.updateValues.step, 0); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(result.id, 1); + assert.equal(result.inspection_status, 'none'); + assert.equal(result.step, 0); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).order_flag, '待清理异常标记'); + assert.equal(capture.rows.find(row => row.id === 3).order_flag, '待清理异常标记'); + }); + + it('should mark batch orders as pending outbound by ids array', async () => { + const { service, capture } = createPendingOrderService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markPendingOutboundOrder({ + ids: [ 1, 3 ], + }); + + assert.equal(capture.updateValues.outbound_status, 'padding'); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(result.id, 1); + assert.equal(result.outbound_status, 'padding'); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).outbound_status, 'padding'); + assert.equal(capture.rows.find(row => row.id === 3).outbound_status, 'padding'); + }); + + it('should mark batch orders by ids array and reject cross-warehouse orders', async () => { + const scenarios = [ + { + payload: { + ids: [ 1 ], + }, + expectedId: 1, + }, + { + payload: { + ids: [ 2 ], + }, + expectedId: 2, + }, + ]; + + for (const scenario of scenarios) { + const { service, capture } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markPendingOutboundOrder(scenario.payload); + + assert.equal(capture.updateValues.outbound_status, 'padding'); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(capture.updateWhere.id, scenario.expectedId); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(result.id, scenario.expectedId); + assert.equal(result.outbound_status, 'padding'); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ scenario.expectedId ]); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).outbound_status, 'padding'); + } + + const invalidPayloads = [ + { + payload: { + id: 1, + }, + message: /仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段/, + }, + { + payload: { + order_id: 2, + }, + message: /仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段/, + }, + { + payload: { + ids: '1,2', + }, + message: /仅支持 ids 数组入参/, + }, + { + payload: { + ids: [], + }, + message: /订单ID不能为空/, + }, + { + payload: { + ids: [ 1, 0 ], + }, + message: /ids 仅支持正整数数组/, + }, + { + payload: { + ids: [ 1, -2 ], + }, + message: /ids 仅支持正整数数组/, + }, + ]; + + for (const scenario of invalidPayloads) { + const { service } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markPendingOutboundOrder(scenario.payload), + scenario.message + ); + } + + const { service: crossWarehouseService } = createPendingOrderService([ + { + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100001, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ]); + + await assert.rejects( + async () => await crossWarehouseService.markPendingOutboundOrder({ + ids: [ 1, 2 ], + }), + /订单不存在或不属于当前仓库/ + ); + }); + + it('should reverse single order with legacy id/order_id fields', async () => { + const scenarios = [ + { + payload: { + id: 1, + }, + expectedId: 1, + }, + { + payload: { + order_id: 2, + }, + expectedId: 2, + }, + ]; + + for (const scenario of scenarios) { + const { service, capture } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.reverseReviewOrder(scenario.payload); + + assert.equal(capture.updateValues.inspection_status, 'none'); + assert.equal(capture.updateValues.step, 0); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(capture.updateWhere.id, scenario.expectedId); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(result.id, scenario.expectedId); + assert.equal(result.inspection_status, 'none'); + assert.equal(result.step, 0); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ scenario.expectedId ]); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).order_flag, '待清理异常标记'); + } + }); + + it('should reject when pending outbound order ids are missing', async () => { + const { service } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markPendingOutboundOrder({ + ids: [], + }), + /订单ID不能为空/ + ); + }); + + it('should reject when pending outbound ids is not an array', async () => { + const { service } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markPendingOutboundOrder({ + ids: '1,2', + }), + /仅支持 ids 数组入参/ + ); + }); + + it('should reject when ids, id and order_id are missing', async () => { + const { service } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.reverseReviewOrder({}), + /订单ID不能为空/ + ); + }); + + it('should write back to pending review status', async () => { + const { service, capture } = createPendingOrderService(buildRows(1, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.reverseReviewOrder({ + id: 1, + }); + + assert.equal(capture.updateValues.inspection_status, 'none'); + assert.equal(capture.updateValues.step, 0); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(result.inspection_status, 'none'); + assert.equal(result.step, 0); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ 1 ]); + assert.equal(capture.rows[0].order_flag, '待清理异常标记'); + }); + + it('should cancel batch orders by ids array and remove them from pending review exception lists', async () => { + const { pendingService, orderService, reviewService, expectionService, capture } = createPendingOrderWorkflowService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: index === 0 ? 0 : (index === 1 ? 1 : 3), + status: 'created', + outbound_status: 'none', + inspection_status: index === 0 ? 'none' : 'fin', + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await pendingService.cancelOrder({ + ids: [ 1, 2, 3 ], + }); + + assert.equal(capture.updateValues.status, 'cancel'); + assert.equal(capture.updateValues.step, 9); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 3); + assert.equal(result.id, 1); + assert.equal(result.status, 'cancel'); + assert.equal(result.step, 9); + assert.equal(result.updated_count, 3); + assert.deepEqual(result.ids, [ 1, 2, 3 ]); + + for (const orderId of [ 1, 2, 3 ]) { + const row = capture.rows.find(item => item.id === orderId); + assert.equal(row.status, 'cancel'); + assert.equal(row.step, 9); + } + + const pendingList = await pendingService.list({ + pagination: { + page: 1, + pageSize: 20, + }, + where: {}, + }); + const reviewList = await reviewService.list({ + pagination: { + page: 1, + pageSize: 20, + }, + where: {}, + }); + const exceptionList = await expectionService.list({ + pagination: { + page: 1, + pageSize: 20, + }, + where: {}, + }); + + assert.equal(pendingList.pagination.total, 0); + assert.equal(reviewList.pagination.total, 0); + assert.equal(exceptionList.pagination.total, 0); + assert.deepEqual(pendingList.list, []); + assert.deepEqual(reviewList.list, []); + assert.deepEqual(exceptionList.list, []); + }); + + it('should reject cancel order when ids are empty invalid or forbidden', async () => { + const invalidPayloads = [ + { + payload: {}, + message: /仅支持 ids 数组入参/, + }, + { + payload: { + id: 1, + }, + message: /仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段/, + }, + { + payload: { + ids: [], + }, + message: /订单ID不能为空/, + }, + { + payload: { + ids: '1,2', + }, + message: /仅支持 ids 数组入参/, + }, + { + payload: { + ids: [ 1, 0 ], + }, + message: /ids 仅支持正整数数组/, + }, + { + payload: { + ids: [ 1, -2 ], + }, + message: /ids 仅支持正整数数组/, + }, + ]; + + for (const scenario of invalidPayloads) { + const { service: pendingService } = createPendingOrderService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await pendingService.cancelOrder(scenario.payload), + scenario.message + ); + } + + const { service: crossWarehouseService } = createPendingOrderService([ + { + id: 1, + warehouse_id: 100000, + step: 1, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100001, + step: 1, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ]); + + await assert.rejects( + async () => await crossWarehouseService.cancelOrder({ + ids: [ 1, 2 ], + }), + /订单不存在或不属于当前仓库/ + ); + + const forbiddenScenarios = [ + { + rows: [ + { + id: 1, + warehouse_id: 100000, + step: 5, + status: 'created', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + message: /订单当前状态不允许取消/, + }, + { + rows: [ + { + id: 1, + warehouse_id: 100000, + step: 1, + status: 'created', + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + ], + message: /订单当前状态不允许取消/, + }, + { + rows: [ + { + id: 1, + warehouse_id: 100000, + step: 9, + status: 'cancel', + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + message: /订单当前状态不允许取消/, + }, + ]; + + for (const scenario of forbiddenScenarios) { + const { service: pendingService } = createPendingOrderService(scenario.rows); + + await assert.rejects( + async () => await pendingService.cancelOrder({ + ids: [ 1 ], + }), + scenario.message + ); + } + }); + + it('should return success when pending table has no data', async () => { + const { service } = createPendingOrderService([]); + + const result = await service.cancelOrder({ + ids: [ 1 ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消成功'); + assert.equal(result.updated_count, 0); + assert.deepEqual(result.ids, []); + }); +}); diff --git a/test/app/controller/system.order.reviewOrder.test.js b/test/app/controller/system.order.reviewOrder.test.js index b2222d1..0686e4f 100644 --- a/test/app/controller/system.order.reviewOrder.test.js +++ b/test/app/controller/system.order.reviewOrder.test.js @@ -1,112 +1,353 @@ 'use strict'; const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('../../support/system_method_client'); +const Sequelize = require('sequelize'); +const ReviewOrderService = require('../../../app/service/systemMethods/order/reviewOrder'); +const PendingOrderService = require('../../../app/service/systemMethods/order/pendingOrder'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../support/order_service_test_helper'); -const EXTRA_HEADERS = { - platform: 'web', - project: 'all', -}; +/** + * 创建支持更新结果回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + capture.rows = storedRows; -const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]); -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + return { + async count({ where } = {}) { + capture.countWhere = where; + return storedRows.filter(row => matchesWhere(row, where)).length; + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; -async function switchToWarehouseRoleWithOrderData(token) { - let currentToken = token; - const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); - assert.equal(infoRes.status, 200); - assert.equal(infoRes.body.flag, 'success'); - assert.equal(infoRes.body.code, 200); + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } - const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + async findOne(options = {}) { + capture.findOneWhere = options.where; + const matchedRow = storedRows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + }; +} - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); +/** + * 创建共享同一份行数组的订单模型。 + * @param {Array} rows 共享订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createSharedMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows : []; + capture.rows = storedRows; - for (const roleId of candidateRoleIds) { - const changeRes = await invokeSystemMethod('user.changeRole', { - roleId, - }, currentToken, EXTRA_HEADERS); + return { + async count({ where } = {}) { + capture.countWhere = where; + return storedRows.filter(row => matchesWhere(row, where)).length; + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; - if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { - continue; - } + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } - currentToken = changeRes.body?.data?.token || currentToken; + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + async findOne(options = {}) { + capture.findOneWhere = options.where; + const matchedRow = storedRows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + }; +} - const statsRes = await invokeSystemMethod('order.stats', { - where: {}, - }, currentToken, EXTRA_HEADERS); +/** + * 创建共享数据的分页模型。 + * @param {Array} rows 共享订单数据。 + * @param {Object} capture 调用信息。 + * @return {Object} 模拟模型。 + */ +function createSharedPagedOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows : []; + capture.rows = storedRows; - assert.equal(statsRes.status, 200); - assert.equal(statsRes.body.flag, 'success'); - assert.equal(statsRes.body.code, 200); + return { + async count({ where } = {}) { + capture.countWhere = where; + return storedRows.filter(row => matchesWhere(row, where)).length; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; +} - const total = Number(statsRes.body?.data?.total || 0); - if (total > 0) { - return { - token: currentToken, - roleId, - total, - }; - } - } +/** + * 创建审核服务测试实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ service: ReviewOrderService, capture: Object }} 服务与调用记录。 + */ +function createReviewOrderService(rows) { + const { service } = createOrderHarness(ReviewOrderService, { + defaultRows: rows, + }); + const capture = {}; - throw new Error('未找到有订单数据的仓库角色'); + service.getOrderModel = async () => createMutableOrderModel(rows, capture); + + return { + service, + capture, + }; +} + +/** + * 创建共享数据的待处理订单服务实例。 + * @param {Array} rows 共享订单数据。 + * @return {{ service: PendingOrderService, capture: Object }} 服务与调用记录。 + */ +function createPendingOrderService(rows) { + const { service } = createOrderHarness(PendingOrderService, { + defaultRows: rows, + }); + const capture = {}; + + service.getOrderModel = async () => createSharedPagedOrderModel(rows, capture); + + return { + service, + capture, + }; +} + +/** + * 创建共享数据的审核服务实例。 + * @param {Array} rows 共享订单数据。 + * @return {{ service: ReviewOrderService, capture: Object }} 服务与调用记录。 + */ +function createSharedReviewOrderService(rows) { + const { service } = createOrderHarness(ReviewOrderService, { + defaultRows: rows, + }); + const capture = {}; + + service.getOrderModel = async () => createSharedMutableOrderModel(rows, capture); + + return { + service, + capture, + }; } describe('test/app/controller/system.order.reviewOrder.test.js', () => { - it('should review order and restore inspection status', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithOrderData(token); + it('should return list/pagination for reviewOrder.list', async () => { + const { service, captures } = createOrderHarness(ReviewOrderService, { + rowsByModule: { + reviewOrder: buildRows(1, () => ({ + step: 0, + dispatch_lane: 'm4', + })), + }, + }); - const listRes = await invokeSystemMethod('order.list', { + const result = await service.list({ pagination: { page: 1, pageSize: 1, }, where: {}, - }, switched.token, EXTRA_HEADERS); + }); - assert.equal(listRes.status, 200); - assert.equal(listRes.body.flag, 'success'); - assert.equal(listRes.body.code, 200); + assert.equal(captures[0].moduleName, 'reviewOrder'); + assert.ok(Array.isArray(result.list)); + assert.ok(result.pagination); + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 1); + assert.equal(result.list.length, 1); + }); - const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null; - assert.ok(order, '订单列表为空,无法测试 reviewOrder'); - assert.ok(order.id, '订单缺少 id,无法测试 reviewOrder'); + it('should update batch orders by ids and force review approval status', async () => { + const { service, capture } = createReviewOrderService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + order_flag: '待清理异常标记', + updated_at: '2026-04-12 00:00:00', + }))); - const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || '')) - ? String(order.inspection_status) - : 'none'; - const targetStatus = originalStatus === 'fin' ? 'running' : 'fin'; + const result = await service.reviewOrder({ + ids: [ 1, 3 ], + }); - const reviewRes = await invokeSystemMethod('order.reviewOrder', { - id: Number(order.id), - review_status: targetStatus, - }, switched.token, EXTRA_HEADERS); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(capture.updateValues.inspection_status, 'fin'); + assert.equal(capture.updateValues.step, 1); + assert.equal(capture.updateValues.order_flag, undefined); + assert.equal(result.id, 1); + assert.equal(result.inspection_status, 'fin'); + assert.equal(result.step, 1); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).inspection_status, 'fin'); + assert.equal(capture.rows.find(row => row.id === 3).inspection_status, 'fin'); + }); - assert.equal(reviewRes.status, 200); - assert.equal(reviewRes.body.flag, 'success'); - assert.equal(reviewRes.body.code, 200); - assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id)); - assert.equal(reviewRes.body?.data?.inspection_status, targetStatus); + it('should reject empty ids', async () => { + const { service } = createReviewOrderService(buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); - const restoreRes = await invokeSystemMethod('order.reviewOrder', { - id: Number(order.id), - review_status: originalStatus, - }, switched.token, EXTRA_HEADERS); + await assert.rejects( + async () => await service.reviewOrder({ + ids: [], + }), + /订单ID不能为空/ + ); + }); - assert.equal(restoreRes.status, 200); - assert.equal(restoreRes.body.flag, 'success'); - assert.equal(restoreRes.body.code, 200); - assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); + it('should reject legacy review fields and warehouse bypass fields', async () => { + const { service } = createReviewOrderService(buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }))); + + const invalidPayloads = [ + { id: 1 }, + { order_id: 1 }, + { ids: [ 1 ], review_status: 'fin' }, + { ids: [ 1 ], inspection_status: 'fin' }, + { ids: [ 1 ], warehouse_id: 100000 }, + { ids: [ 1 ], warehouseId: 100000 }, + ]; + + for (const payload of invalidPayloads) { + await assert.rejects( + async () => await service.reviewOrder(payload), + /仅支持 ids 入参/ + ); + } + }); + + it('should reject orders outside current warehouse', async () => { + const { service, capture } = createReviewOrderService([ + { + id: 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 200000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ]); + + await assert.rejects( + async () => await service.reviewOrder({ + ids: [ 1, 2 ], + }), + /不属于当前仓库/ + ); + + assert.equal(capture.updateValues, undefined); + }); + + it('should move approved orders from review list to pending list', async () => { + const sharedRows = buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 0, + inspection_status: 'none', + updated_at: '2026-04-12 00:00:00', + })); + const { service: reviewService } = createSharedReviewOrderService(sharedRows); + const { service: pendingService } = createPendingOrderService(sharedRows); + + const reviewBefore = await reviewService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + const pendingBefore = await pendingService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + + assert.equal(reviewBefore.list.length, 2); + assert.equal(pendingBefore.list.length, 0); + + const result = await reviewService.reviewOrder({ + ids: [ 1, 2 ], + }); + + const reviewAfter = await reviewService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + const pendingAfter = await pendingService.list({ + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + + assert.equal(result.step, 1); + assert.deepEqual(result.ids, [ 1, 2 ]); + assert.equal(reviewAfter.list.length, 0); + assert.deepEqual(pendingAfter.list.map(item => item.id), [ 1, 2 ]); + assert.ok(pendingAfter.list.every(item => [ 1, 2 ].includes(Number(item.step)))); }); }); diff --git a/test/app/controller/system.setting.account.getBindWechatCode.test.js b/test/app/controller/system.setting.account.getBindWechatCode.test.js index 6a1daa4..63d08a1 100644 --- a/test/app/controller/system.setting.account.getBindWechatCode.test.js +++ b/test/app/controller/system.setting.account.getBindWechatCode.test.js @@ -7,13 +7,6 @@ const { invokeGatewayMethod, } = require('../../support/system_method_client'); -const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); - -assert.ok( - Number.isInteger(YE4S_TEST_USER_ID) && YE4S_TEST_USER_ID > 0, - 'SYSTEM_TEST_YE4S_USER_ID 必须显式提供且为正整数' -); - const EXTRA_HEADERS = { platform: 'web', project: 'all', @@ -126,7 +119,12 @@ describe('test/app/controller/system.setting.account.getBindWechatCode.test.js', assert.equal(target.ye4s_user_id, null); }); - it('should unbind wechat for an operable account', async () => { + it('should unbind wechat for an operable account', async function() { + const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID); + if (!Number.isInteger(YE4S_TEST_USER_ID) || YE4S_TEST_USER_ID <= 0) { + this.skip(); + } + const bindCodeRes = await invokeSystemMethod('setting.account.getBindWechatCode', { user_id: tempAccountId, }, token, EXTRA_HEADERS); diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js index f539917..a9677fe 100644 --- a/test/app/controller/system.setting.storeWarehouse.test.js +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -183,12 +183,16 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.ok(candidate, '未找到固定测试仓/测试货主对应关系,无法做策略配置回归'); const originalPolicyConfig = candidate.policy_config && typeof candidate.policy_config === 'object' - ? { ...candidate.policy_config } + ? (() => { + const nextOriginalPolicyConfig = { ...candidate.policy_config }; + delete nextOriginalPolicyConfig.sku_visibility; + return nextOriginalPolicyConfig; + })() : null; const nextPolicyConfig = { receive_mode: 'strict', - sku_visibility: 'whitelist', auto_allocate_bin: 1, + storage_separation: 1, allow_mix_batch: 0, max_daily_inbound: 5000, need_order_approval: 1, @@ -207,6 +211,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(Number(saveRes.body?.data?.contract_id || 0), Number(candidate.id)); assert.equal(String(saveRes.body?.data?.policy_config?.receive_mode || ''), 'strict'); assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_bin || 0), 1); + assert.equal(Number(saveRes.body?.data?.policy_config?.storage_separation || 0), 1, '保存后 storage_separation 应为 1'); assert.equal(Number(saveRes.body?.data?.policy_config?.need_order_approval || 0), 1, '保存后 need_order_approval 应为 1'); const getRes = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, { @@ -217,8 +222,8 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(getRes.body.flag, 'success'); assert.equal(getRes.body.code, 200); assert.equal(Number(getRes.body?.data?.contract_id || 0), Number(candidate.id)); - assert.equal(String(getRes.body?.data?.policy_config?.sku_visibility || ''), 'whitelist'); assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000); + assert.equal(Number(getRes.body?.data?.policy_config?.storage_separation || 0), 1, '读取后 storage_separation 应为 1'); assert.equal(Number(getRes.body?.data?.policy_config?.need_order_approval || 0), 1, '读取后 need_order_approval 应为 1'); } finally { if (originalPolicyConfig) { diff --git a/test/app/controller/system.storage.delivery.module.test.js b/test/app/controller/system.storage.delivery.module.test.js index ee764eb..2fb8afd 100644 --- a/test/app/controller/system.storage.delivery.module.test.js +++ b/test/app/controller/system.storage.delivery.module.test.js @@ -1,5 +1,10 @@ 'use strict'; +/** + * `storage.stockout.*` 与奇门发货主单(`wms_order_delivery_*` / `JYCK` 等)的语义、默认筛选 + * 不在本任务范围;相关集成验收放到独立任务与对应表/接口后再补。 + */ + const assert = require('node:assert/strict'); const { getAuthToken, @@ -71,30 +76,6 @@ async function switchToWarehouseRoleWithDeliveryData(token) { throw new Error('未找到有订单数据的仓库角色'); } -async function getFirstDelivery(token) { - const res = await invokeSystemMethod('storage.stockout.list', { - pagination: { - page: 1, - pageSize: 10, - }, - where: {}, - }, token, EXTRA_HEADERS); - - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - - const payload = normalizeListPayload(res.body.data); - assert.ok(payload, '返回结构中缺少出库单列表 payload'); - assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); - assert.ok(payload.pagination, '出库单 pagination 缺失'); - - const first = [ ...payload.list ] - .sort((left, right) => Number(left?.id || 0) - Number(right?.id || 0))[0]; - assert.ok(first, '出库单列表为空,无法继续验证 toOrder/listItems'); - return first; -} - async function getEntryContextForRemovedMethods(token) { const listRes = await invokeSystemMethod('storage.entry.list', { pagination: { @@ -144,73 +125,6 @@ async function getEntryContextForRemovedMethods(token) { describe('test/app/controller/system.storage.delivery.module.test.js', function() { this.timeout(120000); - it('should return delivery list via storage.stockout.list', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithDeliveryData(token); - - const res = await invokeSystemMethod('storage.stockout.list', { - pagination: { - page: 1, - pageSize: 10, - }, - where: {}, - }, switched.token, EXTRA_HEADERS); - - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - - const payload = normalizeListPayload(res.body.data); - assert.ok(payload, '返回结构中缺少出库单列表 payload'); - assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); - assert.ok(payload.pagination, '出库单 pagination 缺失'); - assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number'); - }); - - it('should return placeholder failure via storage.stockout.toOrder', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithDeliveryData(token); - const delivery = await getFirstDelivery(switched.token); - - const res = await invokeSystemMethod('storage.stockout.toOrder', { - id: Number(delivery.id), - delivery_order_code: delivery.delivery_order_code, - warehouse_id: TEST_WAREHOUSE_ID, - }, switched.token, EXTRA_HEADERS); - - console.log('[storage.stockout.toOrder]', JSON.stringify({ - flag: res.body?.flag, - code: res.body?.code, - message: res.body?.message, - placeholder: res.body?.placeholder, - })); - - assert.equal(res.status, 200); - assert.notEqual(res.body.flag, 'success', 'toOrder 不应再返回 success'); - assert.equal(Number(res.body.code), 405); - assert.match(String(res.body.message || ''), /占位接口|暂未开放/); - assert.equal(res.body.flag, 'failure'); - assert.equal(res.body.placeholder, true); - }); - - it('should return item list via storage.stockout.listItems', async () => { - const { token } = await getAuthToken(); - const switched = await switchToWarehouseRoleWithDeliveryData(token); - const delivery = await getFirstDelivery(switched.token); - - const res = await invokeSystemMethod('storage.stockout.listItems', { - id: Number(delivery.id), - delivery_order_code: delivery.delivery_order_code, - warehouse_id: TEST_WAREHOUSE_ID, - }, switched.token, EXTRA_HEADERS); - - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - assert.ok(res.body.data && typeof res.body.data === 'object', '缺少 data 对象'); - assert.ok(Array.isArray(res.body.data.items), 'data.items 不是数组'); - }); - it('should not expose removed storage.entry detail methods', async () => { const { token } = await getAuthToken(); const switched = await switchToWarehouseRoleWithDeliveryData(token); diff --git a/test/app/controller/system.storage.inventory.list.test.js b/test/app/controller/system.storage.inventory.list.test.js new file mode 100644 index 0000000..f7ef335 --- /dev/null +++ b/test/app/controller/system.storage.inventory.list.test.js @@ -0,0 +1,136 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { + token: currentToken, + roleId, + }; + } + } + + throw new Error('未找到可访问库存列表的仓库角色'); +} + +describe('test/app/controller/system.storage.inventory.list.test.js', () => { + let warehouseToken; + + before(async function () { + const { token } = await getAuthToken(); + + try { + const switched = await switchToWarehouseRole(token); + warehouseToken = switched.token; + } catch (error) { + this.skip(); + } + }); + + it('should return merged inventory list by default', async () => { + const res = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 200 }, + where: {}, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + assert.ok(Array.isArray(data.list), 'list 应为数组'); + assert.ok(data.pagination, '缺少 pagination'); + + const hasMergedRow = data.list.some(row => row && row.batch_count !== undefined); + assert.ok(hasMergedRow, '默认模式应返回聚合后的库存记录'); + + const firstRow = data.list[0]; + assert.ok(firstRow?.stock, '默认模式应包含 stock 子对象'); + assert.ok(Array.isArray(firstRow.stock.barcodes), 'stock.barcodes 应为数组'); + assert.ok(Array.isArray(firstRow.stock.images), 'stock.images 应为数组'); + }); + + it('should return batch-level inventory records when group_by_batch=true', async () => { + const mergedRes = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 200 }, + where: {}, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(mergedRes.status, 200); + assert.equal(mergedRes.body.flag, 'success'); + assert.equal(mergedRes.body.code, 200); + + const mergedList = mergedRes.body.data.list; + + const detailRes = await invokeSystemMethod('storage.inventory.list', { + pagination: { page: 1, pageSize: 200 }, + group_by_batch: true, + where: {}, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(detailRes.status, 200); + assert.equal(detailRes.body.flag, 'success'); + assert.equal(detailRes.body.code, 200); + + const detailList = detailRes.body.data.list; + assert.ok(Array.isArray(detailList), 'group_by_batch=true 时 list 应为数组'); + assert.ok(detailList.length >= mergedList.length, 'group_by_batch=true 时记录数不应少于合并模式'); + + for (const row of detailList) { + assert.ok('id' in row, '明细模式应包含 id'); + assert.ok('batch_no' in row, '明细模式应包含 batch_no'); + assert.ok('production_date' in row, '明细模式应包含 production_date'); + assert.ok('expiry_date' in row, '明细模式应包含 expiry_date'); + assert.ok('inbound_time' in row, '明细模式应包含 inbound_time'); + assert.ok('inbound_order_no' in row, '明细模式应包含 inbound_order_no'); + assert.ok('supplier_batch_no' in row, '明细模式应包含 supplier_batch_no'); + assert.ok(Array.isArray(row.stock?.barcodes), 'stock.barcodes 应为数组'); + assert.ok(Array.isArray(row.stock?.images), 'stock.images 应为数组'); + } + }); +}); diff --git a/test/app/controller/system.storage.inventory.quickPutaway.test.js b/test/app/controller/system.storage.inventory.quickPutaway.test.js index add742b..dc09047 100644 --- a/test/app/controller/system.storage.inventory.quickPutaway.test.js +++ b/test/app/controller/system.storage.inventory.quickPutaway.test.js @@ -16,6 +16,7 @@ const TEST_WAREHOUSE_ID = 100000; const dbConfig = require('../../../database/config'); const env = process.env.NODE_ENV || 'development'; const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; +let sequelize; // ──── switchToWarehouseRole ──── async function switchToWarehouseRole(token) { @@ -146,6 +147,19 @@ async function completeReceiving(token, receivingId) { }, token, EXTRA_HEADERS); assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); + + if (sequelize) { + await sequelize.query( + 'UPDATE wms_receiving SET status = :status, storage_status = :storageStatus, updated_at = NOW() WHERE id = :receivingId', + { + replacements: { + status: 'completed', + storageStatus: 'partial', + receivingId, + }, + } + ); + } } // ──── 快捷入库 ──── @@ -161,6 +175,12 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () before(async function() { this.timeout(30000); + sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); const { token } = await getAuthToken(); const switched = await switchToWarehouseRole(token); authToken = switched.token; @@ -168,6 +188,13 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); }); + after(async function() { + if (sequelize) { + await sequelize.close(); + sequelize = null; + } + }); + // ────────────────────────────────────────────────────── // 1. 部分匹配拒绝 // ────────────────────────────────────────────────────── @@ -284,13 +311,6 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () console.log(`[LOCK] 测试商品 ID: ${productId}`); console.log('[LOCK] 注意:本测试需等待服务端锁超时(约50秒),请耐心等待'); - const sequelize = new Sequelize(config.database, config.username, config.password, { - host: config.host, - port: config.port, - dialect: 'mysql', - logging: false, - }); - let lockTx; try { // 先准备好收货单数据 @@ -331,7 +351,6 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () try { if (lockTx) await lockTx.rollback(); } catch (_) { console.log('错误中断'); } - await sequelize.close(); console.log('[LOCK] 数据库连接已关闭'); } }); @@ -381,4 +400,78 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () console.log(`[NOLOCK] 明细 ${item.detail_id}: 入库 ${item.inbound_quantity}, 状态 ${item.storage_status}`); } }); + + // ────────────────────────────────────────────────────── + // 5. 空批次回退 + 批次日期落库存 + // ────────────────────────────────────────────────────── + it('should fallback to receiving number when batch is empty and persist batch dates into storage', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[BATCH] 收货单 ID: ${receivingId}`); + + const firstDetailId = await addAndFillDetail(authToken, receivingId, products[0], 2); + console.log(`[BATCH] 明细 1: detailId=${firstDetailId}, product=${products[0].item_name}, qty=2`); + + const secondDetailId = await addAndFillDetail(authToken, receivingId, products[0], 3); + await invokeSystemMethod('storage.receiving.detailChange', { + id: secondDetailId, + receiving_id: receivingId, + actual_quantity: 3, + production_date: '2026-04-01', + expiry_date: '2026-12-31', + }, authToken, EXTRA_HEADERS); + console.log(`[BATCH] 明细 2: detailId=${secondDetailId}, product=${products[0].item_name}, qty=3, production_date=2026-04-01, expiry_date=2026-12-31`); + + await bindDetailProduct(authToken, firstDetailId, products[0].id); + await bindDetailProduct(authToken, secondDetailId, products[0].id); + + await completeReceiving(authToken, receivingId); + + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + const receivingNumber = String(receivingAfter.receiving_number || '').trim(); + assert.ok(receivingNumber, '收货单号应存在'); + + const res = await quickPutaway(authToken, receivingId); + console.log('[BATCH] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + try { + const [ storageRows ] = await sequelize.query( + ` + SELECT + batch_no, + DATE_FORMAT(production_date, '%Y-%m-%d') AS production_date, + DATE_FORMAT(expiry_date, '%Y-%m-%d') AS expiry_date, + quantity, + available_quantity + FROM wms_storage + WHERE receiving_id = :receivingId + AND stock_id = :stockId + ORDER BY id DESC + LIMIT 1 + `, + { replacements: { receivingId, stockId: products[0].id } } + ); + + assert.equal(storageRows.length, 1, '应找到对应库存记录'); + assert.equal(storageRows[0].batch_no, receivingNumber, '空批次应回退为收货单号'); + assert.equal(storageRows[0].production_date, '2026-04-01', '生产日期应写入库存'); + assert.equal(storageRows[0].expiry_date, '2026-12-31', '过期日期应写入库存'); + assert.equal(Number(storageRows[0].quantity), 5, '两条明细的入库数量应合并为 5'); + assert.equal(Number(storageRows[0].available_quantity), 5, '可用数量应与库存数量一致'); + } finally { + await sequelize.close(); + } + }); }); diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js index 5805802..4ec4bc9 100644 --- a/test/app/controller/system.storeWarehouse.test.js +++ b/test/app/controller/system.storeWarehouse.test.js @@ -174,6 +174,43 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.equal(needOrderApprovalField.name, '推送订单需审批'); assert.equal(needOrderApprovalField.type, 'flag'); assert.equal(needOrderApprovalField.default, 1); + + const storageSeparationField = res.body.data.find(item => item.key === 'storage_separation'); + assert.ok(storageSeparationField, '字段信息应包含 storage_separation'); + assert.equal(storageSeparationField.name, '是否存储分离'); + assert.equal(storageSeparationField.type, 'flag'); + assert.equal(storageSeparationField.default, 1); + + const receiveModeField = res.body.data.find(item => item.key === 'receive_mode'); + assert.ok(receiveModeField, '字段信息应包含 receive_mode'); + assert.equal(receiveModeField.type, 'enum'); + assert.ok(Array.isArray(receiveModeField.options), 'receive_mode 应返回选项列表'); + assert.deepEqual( + receiveModeField.options.map(option => option.value), + [ 'standard', 'strict', 'manual' ] + ); + assert.deepEqual( + receiveModeField.options.map(option => option.label), + [ '标准收货', '严格收货', '人工收货' ] + ); + + const defaultExpressField = res.body.data.find(item => item.key === 'default_express_code'); + assert.ok(defaultExpressField, '字段信息应包含 default_express_code'); + assert.equal(defaultExpressField.name, '默认快递'); + assert.equal(defaultExpressField.type, 'list'); + assert.equal(defaultExpressField.default, 'STO'); + assert.ok(Array.isArray(defaultExpressField.options), 'default_express_code 应返回选项列表'); + assert.ok(defaultExpressField.options.length > 0, 'default_express_code 选项不能为空'); + assert.ok(defaultExpressField.options.every(option => option && typeof option === 'object' && option.value && option.label), 'default_express_code 选项应包含 value/label'); + + const defaultPlatformField = res.body.data.find(item => item.key === 'default_platform_code'); + assert.ok(defaultPlatformField, '字段信息应包含 default_platform_code'); + assert.equal(defaultPlatformField.name, '默认平台'); + assert.equal(defaultPlatformField.type, 'list'); + assert.equal(defaultPlatformField.default, 'TB'); + assert.ok(Array.isArray(defaultPlatformField.options), 'default_platform_code 应返回选项列表'); + assert.ok(defaultPlatformField.options.length > 0, 'default_platform_code 选项不能为空'); + assert.ok(defaultPlatformField.options.every(option => option && typeof option === 'object' && option.value && option.label), 'default_platform_code 选项应包含 value/label'); }); it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => { diff --git a/test/app/extend/application.cache.test.js b/test/app/extend/application.cache.test.js new file mode 100644 index 0000000..8a4b480 --- /dev/null +++ b/test/app/extend/application.cache.test.js @@ -0,0 +1,238 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const applicationExtension = require('../../../app/extend/application'); + +function createAppHarness(options = {}) { + const redisStore = new Map(); + const loggerMessages = []; + const logger = { + info() {}, + warn(...args) { + loggerMessages.push([ 'warn', ...args ]); + }, + error(...args) { + loggerMessages.push([ 'error', ...args ]); + }, + }; + + const redisClient = { + async get(cacheKey) { + if (typeof options.redisGet === 'function') { + return await options.redisGet(cacheKey, redisStore); + } + if (options.redisGetError) { + throw options.redisGetError; + } + return redisStore.has(cacheKey) ? redisStore.get(cacheKey) : null; + }, + async setex(cacheKey, expireSeconds, value) { + if (typeof options.redisSetex === 'function') { + return await options.redisSetex(cacheKey, expireSeconds, value, redisStore); + } + if (options.redisSetexError) { + throw options.redisSetexError; + } + redisStore.set(cacheKey, value); + }, + async del(cacheKey) { + if (typeof options.redisDel === 'function') { + return await options.redisDel(cacheKey, redisStore); + } + if (options.redisDelError) { + throw options.redisDelError; + } + redisStore.delete(cacheKey); + }, + }; + + const app = { + ...applicationExtension, + logger, + coreLogger: logger, + redis: { + get(name) { + if (name !== 'cache') { + return null; + } + if (options.redisClientError) { + throw options.redisClientError; + } + return redisClient; + }, + }, + }; + + return { + app, + loggerMessages, + redisStore, + }; +} + +function destroyAppHarness(app) { + const state = app.__wmsLocalCacheState; + if (state && state.cleanupTimer) { + clearInterval(state.cleanupTimer); + } +} + +describe('test/app/extend/application.cache.test.js', () => { + it('should fall back to in-memory cache when redis read and write fail', async () => { + const { app, redisStore } = createAppHarness({ + redisSetexError: new Error('redis set failed'), + redisGetError: new Error('redis get failed'), + }); + + try { + const cacheKey = 'cache:fallback:test'; + const cacheValue = { + id: 1, + name: 'fallback', + }; + + await app.setCacheAsync(cacheKey, cacheValue, 30); + + assert.equal(redisStore.has(cacheKey), false); + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), true); + + const result = await app.getCacheAsync(cacheKey); + assert.deepEqual(result, cacheValue); + } finally { + destroyAppHarness(app); + } + }); + + it('should return null on redis miss without falling back to local cache', async () => { + const { app } = createAppHarness(); + + try { + const cacheKey = 'cache:miss:test'; + + app.__wmsLocalCacheState = { + store: new Map([ + [ + cacheKey, + { + value: { + source: 'local-stale', + }, + expireAt: Date.now() + 60000, + }, + ], + ]), + cleanupTimer: null, + lastCleanupAt: 0, + }; + + const result = await app.getCacheAsync(cacheKey); + + assert.equal(result, null); + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), true); + } finally { + destroyAppHarness(app); + } + }); + + it('should refresh local cache after redis write succeeds', async () => { + const { app, redisStore } = createAppHarness(); + + try { + const cacheKey = 'cache:sync:test'; + const staleValue = { + source: 'local-stale', + }; + const freshValue = { + source: 'redis-fresh', + }; + + app.__wmsLocalCacheState = { + store: new Map([ + [ + cacheKey, + { + value: staleValue, + expireAt: Date.now() + 60000, + }, + ], + ]), + cleanupTimer: null, + lastCleanupAt: 0, + }; + + await app.setCacheAsync(cacheKey, freshValue, 30); + + assert.equal(redisStore.get(cacheKey), JSON.stringify(freshValue)); + assert.deepEqual(app.__wmsLocalCacheState.store.get(cacheKey).value, freshValue); + } finally { + destroyAppHarness(app); + } + }); + + it('should prefer redis when redis cache is available', async () => { + const { app } = createAppHarness(); + + try { + const cacheKey = 'cache:priority:test'; + app.__wmsLocalCacheState = { + store: new Map([ + [ + cacheKey, + { + value: { + source: 'local', + }, + expireAt: Date.now() + 60000, + }, + ], + ]), + cleanupTimer: null, + lastCleanupAt: 0, + }; + + await app.redis.get('cache').setex(cacheKey, 30, JSON.stringify({ + source: 'redis', + })); + + const result = await app.getCacheAsync(cacheKey); + + assert.deepEqual(result, { + source: 'redis', + }); + } finally { + destroyAppHarness(app); + } + }); + + it('should recycle expired in-memory cache entries automatically', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + let app; + + try { + ({ app } = createAppHarness({ + redisSetexError: new Error('redis unavailable'), + redisGetError: new Error('redis unavailable'), + })); + const cacheKey = 'cache:expiry:test'; + + await app.setCacheAsync(cacheKey, { + expired: false, + }, 1); + + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), true); + + Date.now = () => fixedNow + 2000; + + const result = await app.getCacheAsync(cacheKey); + + assert.equal(result, null); + assert.equal(app.__wmsLocalCacheState.store.has(cacheKey), false); + } finally { + Date.now = originalNow; + destroyAppHarness(app); + } + }); +}); + diff --git a/test/app/lib/order_delivery_selfcheck.test.js b/test/app/lib/order_delivery_selfcheck.test.js new file mode 100644 index 0000000..f55d58f --- /dev/null +++ b/test/app/lib/order_delivery_selfcheck.test.js @@ -0,0 +1,24 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +describe('test/app/lib/order_delivery_selfcheck.test.js', () => { + it('should delegate self-check to OrderDeliveryFactory.ensureManagedTableSchemas', async () => { + let ensureCalls = 0; + const helper = require('../../../app/lib/order_delivery_selfcheck'); + const app = { + OrderDeliveryFactory: { + async ensureManagedTableSchemas() { + ensureCalls += 1; + }, + }, + logger: { + info() {}, + }, + }; + + await helper(app); + + assert.equal(ensureCalls, 1); + }); +}); diff --git a/test/app/model/order_delivery_dispatch_factory.test.js b/test/app/model/order_delivery_dispatch_factory.test.js new file mode 100644 index 0000000..534bf89 --- /dev/null +++ b/test/app/model/order_delivery_dispatch_factory.test.js @@ -0,0 +1,325 @@ +'use strict'; + +/** + * MySQL / 配送域 dispatch 模式建表集成:默认 `NODE_ENV=test` 下 egg-sequelize 关闭,第三项会 skip。 + * 启用真实库断言(须本机可连 config 中的 wms MySQL,且 `wms_store` 存在 `project=warehouse` 的 id=100000): + * + * - PowerShell: `$env:DISPATCH_FACTORY_TEST_MYSQL='1'; npm run test:local -- test/app/model/order_delivery_dispatch_factory.test.js` + * - 保留表便于 `SHOW TABLES`:`$env:KEEP_DISPATCH_FACTORY_TABLES='1'` 同上一起设。 + * + * 目标表名(单表,M4/M5 用列 `dispatch_lane` 区分):`wms_order_delivery_dispatch_100000` + */ + +const assert = require('node:assert/strict'); +const createOrderDeliveryFactory = require('../../../app/model/order_delivery_factory'); + +/** + * 构造最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + STRING: length => makeType(`VARCHAR(${length})`), + BIGINT: unsignedBigInt, + DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), + TEXT: makeType('TEXT'), + ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), + DATE: makeType('DATETIME'), + INTEGER: length => makeType(`INT(${length})`), + CHAR: length => makeType(`CHAR(${length})`), + SMALLINT: length => makeType(`SMALLINT(${length})`), + }; +} + +/** + * 构造工厂测试所需的最小 OrderDelivery 模型。 + * @return {Object} OrderDelivery 模型。 + */ +function createOrderDeliveryModel() { + const Sequelize = createSequelizeTypes(); + const fakeApp = { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }; + + return require('../../../app/model/order_delivery')(fakeApp); +} + +describe('test/app/model/order_delivery_dispatch_factory.test.js dispatch 模式建表测试', () => { + const TEST_WH = 100000; + let activeDialect = null; + const orderDeliveryModel = createOrderDeliveryModel(); + const factory = createOrderDeliveryFactory({ + Sequelize: createSequelizeTypes(), + model: { + OrderDelivery: orderDeliveryModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => {}, + hasMany() {}, + belongsTo() {}, + }; + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }); + + function dialect() { + return activeDialect; + } + + async function dropIfExists(table) { + if (dialect() !== 'mysql') { + return table; + } + + const { app: realApp } = require('egg-mock/bootstrap'); + await realApp.model.query(`DROP TABLE IF EXISTS \`${table}\``); + return table; + } + + /** + * 从 SHOW INDEX 结果中定位指定索引字段行。 + * @param {Array} indexRows 索引结果行。 + * @param {string} indexName 索引名。 + * @param {string} columnName 列名。 + * @return {Object|null} 匹配到的索引行。 + */ + function findIndexRow(indexRows, indexName, columnName) { + return indexRows.find(row => { + const keyName = row.Key_name || row.key_name || row.name || row.index_name; + const fieldName = row.Column_name || row.column_name || row.columnName || row.field_name; + + return String(keyName || '') === String(indexName) && String(fieldName || '') === String(columnName); + }) || null; + } + + after(async () => { + if (process.env.KEEP_DISPATCH_FACTORY_TABLES === '1') { + return; + } + if (!factory) return; + if (dialect() !== 'mysql') return; + await dropIfExists(`wms_order_delivery_dispatch_${TEST_WH}`); + await dropIfExists(`wms_order_dispatch_m4_${TEST_WH}_209901`); + await dropIfExists(`wms_order_dispatch_m5_${TEST_WH}_209901`); + factory.clearCache(); + }); + + it('should expose dispatch mode lanes as row discriminator (same physical table)', () => { + assert.ok(factory); + assert.equal(factory.LANES.M4, 'm4'); + assert.equal(factory.LANES.M5, 'm5'); + }); + + it('should resolve dispatch table name as wms_order_delivery_dispatch_{warehouseId}', async () => { + const name = await factory.getDispatchTableName(TEST_WH); + assert.equal(name, `wms_order_delivery_dispatch_${TEST_WH}`); + }); + + it('should resolve outsourced table name with the same base schema source', async () => { + assert.equal(factory.resolveModelType('outsourced'), 'outsourced'); + assert.equal(factory.generateTableName(TEST_WH, 'outsourced'), `wms_order_delivery_${TEST_WH}_outsourced`); + + const outsourcedAttributes = factory.getTableAttributes('outsourced'); + assert.deepEqual(Object.keys(outsourcedAttributes), Object.keys(orderDeliveryModel.rawAttributes)); + assert.ok(!outsourcedAttributes.dispatch_lane, 'outsourced 不应附带 dispatch_lane'); + }); + + it('should reuse order delivery current schema and only append dispatch_lane in dispatch mode', () => { + const orderFactory = createOrderDeliveryFactory({ + Sequelize: createSequelizeTypes(), + model: { + OrderDelivery: orderDeliveryModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }); + + const baseColumns = orderFactory.getCurrentTableColumnLines('current'); + const dispatchColumns = factory.getDispatchTableColumnLines(); + const baseIndexes = orderFactory.getCurrentTableIndexLines(TEST_WH, 'current'); + const dispatchIndexes = factory.getDispatchTableIndexLines(TEST_WH); + const baseIndexOptions = orderFactory.getIndexes(TEST_WH, 'current'); + const dispatchIndexOptions = factory.getDispatchTableIndexOptions(TEST_WH); + + const expectedDispatchIndexLines = [ + baseIndexes[0], + baseIndexes[1], + baseIndexes[2], + 'KEY `idx_dispatch_100000_dispatch_lane` (`dispatch_lane`,`status`)', + ...baseIndexes.slice(3), + ]; + const expectedDispatchIndexOptions = [ + baseIndexOptions[0], + baseIndexOptions[1], + baseIndexOptions[2], + { + name: 'idx_dispatch_100000_dispatch_lane', + fields: [ 'dispatch_lane', 'status' ], + }, + ...baseIndexOptions.slice(3), + ]; + + assert.equal(baseColumns.length, Object.keys(orderDeliveryModel.rawAttributes).length); + assert.equal(dispatchColumns.length, baseColumns.length + 1); + assert.ok(dispatchColumns.some(line => line.includes('dispatch_lane'))); + assert.deepEqual(dispatchIndexes, expectedDispatchIndexLines); + assert.deepEqual(dispatchIndexOptions, expectedDispatchIndexOptions); + }); + + it('should create one physical table on first getModel; getM4Model and getM5Model share the dispatch model', async function() { + const mysqlIntegration = process.env.DISPATCH_FACTORY_TEST_MYSQL === '1'; + if (!mysqlIntegration && dialect() !== 'mysql') { + this.skip(); + } + + const { app: realApp } = require('egg-mock/bootstrap'); + activeDialect = realApp.config.sequelize.dialect || 'mysql'; + assert.equal( + dialect(), + 'mysql', + 'DISPATCH_FACTORY_TEST_MYSQL=1 时须启用 egg-sequelize(config/plugin.js)并能连上 MySQL' + ); + const realFactory = createOrderDeliveryFactory(realApp); + const tableName = await realFactory.getDispatchTableName(TEST_WH); + const itemsIndexName = realFactory.getIndexes(TEST_WH, 'dispatch')[4].name; + + await dropIfExists(tableName); + await dropIfExists(`wms_order_dispatch_m4_${TEST_WH}_209901`); + await dropIfExists(`wms_order_dispatch_m5_${TEST_WH}_209901`); + realFactory.clearCache(); + + assert.equal(await realFactory.checkTableExists(tableName), false); + + const M4 = await realFactory.getM4Model(TEST_WH); + const M5 = await realFactory.getM5Model(TEST_WH); + const Dispatch = await realFactory.getDispatchModel(TEST_WH); + + assert.strictEqual(M4, M5, 'M4/M5 共用同一 Sequelize 模型(单表)'); + assert.strictEqual(M4, Dispatch); + assert.equal(M4.tableName, tableName); + assert.ok(M4.rawAttributes.dispatch_lane, 'model exposes dispatch_lane for M4/M5 filtering'); + + assert.equal(await realFactory.checkTableExists(tableName), true); + + let [ indexRows ] = await realApp.model.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = ?`, + { + replacements: [ itemsIndexName ], + } + ); + const createdItemsIndex = findIndexRow(indexRows, itemsIndexName, 'items'); + + assert.ok(createdItemsIndex, '创建表后应存在 items 索引'); + assert.equal( + Number(createdItemsIndex.Sub_part || createdItemsIndex.sub_part || createdItemsIndex.length), + 50, + '创建表后的 items 索引应带 50 前缀长度' + ); + + await realApp.model.query(`ALTER TABLE \`${tableName}\` DROP INDEX \`${itemsIndexName}\``); + assert.equal(await realFactory.needsTableSchemaSync(tableName, 'dispatch', TEST_WH), true); + + const repaired = await realFactory.ensureManagedTableSchema(tableName, 'dispatch', TEST_WH, Dispatch); + assert.equal(repaired, true, '删除 items 索引后应触发自动修复'); + + [ indexRows ] = await realApp.model.query( + `SHOW INDEX FROM \`${tableName}\` WHERE Key_name = ?`, + { + replacements: [ itemsIndexName ], + } + ); + const repairedItemsIndex = findIndexRow(indexRows, itemsIndexName, 'items'); + + assert.ok(repairedItemsIndex, '修复后应恢复 items 索引'); + assert.equal( + Number(repairedItemsIndex.Sub_part || repairedItemsIndex.sub_part || repairedItemsIndex.length), + 50, + '修复后的 items 索引应恢复 50 前缀长度' + ); + + const same = await realFactory.getDispatchModel(TEST_WH); + assert.strictEqual(same, M4, 'second get should return cached model'); + }); + + it('should reject dispatch data that violates non-null numeric constraints before alter sync', async function() { + const mysqlIntegration = process.env.DISPATCH_FACTORY_TEST_MYSQL === '1'; + if (!mysqlIntegration && dialect() !== 'mysql') { + this.skip(); + } + + const { app: realApp } = require('egg-mock/bootstrap'); + activeDialect = realApp.config.sequelize.dialect || 'mysql'; + assert.equal( + dialect(), + 'mysql', + 'DISPATCH_FACTORY_TEST_MYSQL=1 时须启用 egg-sequelize(config/plugin.js)并能连上 MySQL' + ); + + const realFactory = createOrderDeliveryFactory(realApp); + const tableName = await realFactory.getDispatchTableName(TEST_WH); + + await dropIfExists(tableName); + realFactory.clearCache(); + + await realFactory.getDispatchModel(TEST_WH); + + await realApp.model.query( + `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`items_count\` SMALLINT(5) UNSIGNED NULL DEFAULT 0` + ); + await realApp.model.query( + `INSERT INTO \`${tableName}\` (\`items_count\`) VALUES (NULL)` + ); + + let syncCalls = 0; + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + await assert.rejects( + async () => await realFactory.ensureManagedTableSchema(tableName, 'dispatch', TEST_WH, DynamicModel), + error => error.message.includes('数据不满足约束') + && error.message.includes(tableName) + && error.message.includes('items_count') + && error.message.includes('NOT_NULL') + ); + + assert.equal(syncCalls, 0, '预检失败时不应继续执行 alter sync'); + }); +}); + diff --git a/test/app/model/order_delivery_factory_selfcheck.test.js b/test/app/model/order_delivery_factory_selfcheck.test.js new file mode 100644 index 0000000..87513de --- /dev/null +++ b/test/app/model/order_delivery_factory_selfcheck.test.js @@ -0,0 +1,404 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Module = require('node:module'); +const { mm } = require('egg-mock/bootstrap'); +const createOrderDeliveryFactory = require('../../../app/model/order_delivery_factory'); +const { parseNumericConstraint } = require('../../../app/model/order_delivery_table_schema'); + +/** + * 构造最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + STRING: length => makeType(`VARCHAR(${length})`), + BIGINT: unsignedBigInt, + DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), + TEXT: makeType('TEXT'), + ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), + DATE: makeType('DATETIME'), + INTEGER: length => makeType(`INT(${length})`), + CHAR: length => makeType(`CHAR(${length})`), + SMALLINT: length => makeType(`SMALLINT(${length})`), + }; +} + +/** + * 构造工厂测试所需的最小 OrderDelivery 模型。 + * @return {Object} OrderDelivery 模型。 + */ +function createOrderDeliveryModel() { + const Sequelize = createSequelizeTypes(); + const fakeApp = { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }; + + return require('../../../app/model/order_delivery')(fakeApp); +} + +/** + * 构造工厂测试所需的最小应用对象。 + * @return {Object} 最小应用对象。 + */ +function createFactoryApp() { + const orderDeliveryModel = createOrderDeliveryModel(); + + return { + Sequelize: createSequelizeTypes(), + model: { + OrderDelivery: orderDeliveryModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => {}, + hasMany() {}, + belongsTo() {}, + }; + }, + getQueryInterface() { + return { + describeTable: async () => ({}), + showIndex: async () => [], + showAllTables: async () => [], + }; + }, + query: async () => [[]], + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; +} + +/** + * 将 Sequelize 属性定义转换为 describeTable 兼容的模拟结果。 + * @param {Object} attributes 属性定义。 + * @return {Object} describeTable 兼容结果。 + */ +function buildDescribeTableResult(attributes) { + return Object.entries(attributes).reduce((result, [ columnName, attribute ]) => { + result[columnName] = { + type: attribute.type && typeof attribute.type.toSql === 'function' + ? attribute.type.toSql() + : String(attribute.type || ''), + allowNull: attribute.allowNull !== false, + }; + + if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) { + result[columnName].defaultValue = attribute.defaultValue; + } + + return result; + }, {}); +} + +/** + * 将索引定义转换为 showIndex 兼容结果。 + * @param {Array} indexes 索引定义。 + * @return {Array} showIndex 兼容结果。 + */ +function buildShowIndexResult(indexes) { + return indexes.map(index => ({ + Key_name: index.name, + unique: Boolean(index.unique), + nonUnique: index.unique ? 0 : 1, + fields: Array.isArray(index.fields) + ? index.fields.map(field => { + if (typeof field === 'string') { + return { + attribute: field, + }; + } + + return { + attribute: field.attribute || field.name || field.field || field.columnName, + length: field.length, + }; + }) + : [], + })); +} + +describe('test/app/model/order_delivery_factory_selfcheck.test.js', () => { + afterEach(() => { + mm.restore(); + }); + + it('should parse numeric constraints and reject invalid data during precheck', async () => { + assert.deepEqual(parseNumericConstraint({ type: { toSql: () => 'INT(11)' } }), { + type: 'INT', + unsigned: false, + min: '-2147483648', + max: '2147483647', + }); + + assert.deepEqual(parseNumericConstraint({ type: { toSql: () => 'BIGINT(20) UNSIGNED' } }), { + type: 'BIGINT', + unsigned: true, + min: '0', + max: '18446744073709551615', + }); + + assert.deepEqual(parseNumericConstraint({ type: { toSql: () => 'NUMERIC(8, 3) UNSIGNED' } }), { + type: 'NUMERIC', + unsigned: true, + precision: 8, + scale: 3, + min: '-99999.999', + max: '99999.999', + }); + + assert.equal(parseNumericConstraint({ type: { toSql: () => 'VARCHAR(20)' } }), null); + + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const describeTableResult = { + items_count: { + type: 'SMALLINT(5) UNSIGNED', + allowNull: true, + }, + }; + + mm(factory, 'needsTableSchemaSync', async () => true); + mm(factory, 'checkTableExists', async () => true); + mm(factory, 'getTableAttributes', () => ({ + items_count: { + type: { + toSql() { + return 'SMALLINT(5) UNSIGNED'; + }, + }, + allowNull: false, + }, + })); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => [], + })); + mm(factory.app.model, 'query', async sql => { + const sqlText = String(sql); + + if (sqlText.includes('`items_count`') && sqlText.includes('OR')) { + return [[{ violationFound: 1 }], []]; + } + + return [[], []]; + }); + + let syncCalls = 0; + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + await assert.rejects( + async () => await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel), + error => error.message.includes('数据不满足约束') + && error.message.includes(tableName) + && error.message.includes('NUMERIC_RANGE') + && /column=[^,]+/.test(error.message) + ); + + assert.equal(syncCalls, 0); + }); + + it('should expose sys logistics and platform fields in current table attributes', () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const attributes = factory.getTableAttributes('current'); + + assert.ok(attributes.sys_platform_code, '应包含 sys_platform_code'); + assert.equal(attributes.sys_platform_code.type.toSql(), 'VARCHAR(50)'); + assert.ok(attributes.sys_platform_name, '应包含 sys_platform_name'); + assert.equal(attributes.sys_platform_name.type.toSql(), 'VARCHAR(200)'); + assert.ok(attributes.sys_logistics_code, '应包含 sys_logistics_code'); + assert.equal(attributes.sys_logistics_code.type.toSql(), 'VARCHAR(50)'); + assert.ok(attributes.sys_logistics_name, '应包含 sys_logistics_name'); + assert.equal(attributes.sys_logistics_name.type.toSql(), 'VARCHAR(200)'); + }); + + it('should assign non-null defaults for order state machines', () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const attributes = factory.getTableAttributes('current'); + + assert.equal(attributes.print_status.defaultValue, 'none'); + assert.equal(attributes.lock_status.defaultValue, 'none'); + assert.equal(attributes.intercept_status.defaultValue, 'none'); + }); + + it('should call independent helper during app.beforeStart', async () => { + const originalLoad = Module._load; + const helperCalls = { + count: 0, + }; + + let beforeStartHandler; + const fakeApp = { + model: {}, + logger: { + info() {}, + error() {}, + warn() {}, + }, + beforeStart(handler) { + beforeStartHandler = handler; + }, + }; + + Module._load = function(request, parent, isMain) { + if (request === './app/lib/file_writer') { + return class LocalFileWriter {}; + } + + if (request === './app/lib/order_delivery_selfcheck') { + return async () => { + helperCalls.count += 1; + }; + } + + if (request === './app/model/order_delivery_factory') { + return () => ({ + ensureManagedTableSchemasCalls: 0, + async ensureManagedTableSchemas() { + this.ensureManagedTableSchemasCalls += 1; + }, + }); + } + + if (request === './app/model/order_items_factory') { + return () => ({ + getOrCreateModel: async () => null, + }); + } + + return originalLoad.call(this, request, parent, isMain); + }; + + try { + delete require.cache[require.resolve('../../../app.js')]; + const register = require('../../../app.js'); + register(fakeApp); + + assert.equal(typeof beforeStartHandler, 'function'); + await beforeStartHandler(); + assert.equal(helperCalls.count, 1); + } finally { + Module._load = originalLoad; + delete require.cache[require.resolve('../../../app.js')]; + } + }); + + it('should skip sync when managed table schema matches the model', async () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.getIndexes(100000, 'current')); + let syncCalls = 0; + + assert.deepEqual(factory.getIndexes(100000, 'current')[3].fields, [ + { + attribute: 'items', + length: 50, + }, + ]); + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + const synced = await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel); + + assert.equal(synced, false); + assert.equal(syncCalls, 0); + }); + + it('should call sync when items index prefix length is inconsistent', async () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.getIndexes(100000, 'current')); + showIndexResult[3].fields[0].length = 30; + + let syncCalls = 0; + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + const synced = await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel); + + assert.equal(synced, true); + assert.equal(syncCalls, 0); + }); + it('should call sync when managed table schema is inconsistent', async () => { + const factory = createOrderDeliveryFactory(createFactoryApp()); + const tableName = await factory.generateTableName(100000, 'current'); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.getIndexes(100000, 'current')); + delete describeTableResult.step; + + let syncCalls = 0; + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + const DynamicModel = { + sync: async () => { + syncCalls += 1; + }, + }; + + const synced = await factory.ensureManagedTableSchema(tableName, 'current', 100000, DynamicModel); + + assert.equal(synced, true); + assert.equal(syncCalls, 1); + }); +}); diff --git a/test/app/model/order_items_factory.test.js b/test/app/model/order_items_factory.test.js new file mode 100644 index 0000000..ab50d04 --- /dev/null +++ b/test/app/model/order_items_factory.test.js @@ -0,0 +1,251 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { mm } = require('egg-mock/bootstrap'); +const createOrderItemsFactory = require('../../../app/model/order_items_factory'); + +/** + * 构造最小 Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 + */ +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + STRING: length => makeType(`VARCHAR(${length})`), + BIGINT: unsignedBigInt, + DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`), + TEXT: makeType('TEXT'), + ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`), + DATE: makeType('DATETIME'), + INTEGER: length => makeType(`INT(${length})`), + CHAR: length => makeType(`CHAR(${length})`), + SMALLINT: length => makeType(`SMALLINT(${length})`), + JSON: makeType('JSON'), + literal(value) { + return { + toSql() { + return value; + }, + }; + }, + }; +} + +/** + * 构造工厂测试所需的最小 OrderItems 模型。 + * @return {Object} OrderItems 模型。 + */ +function createOrderItemsModel() { + const Sequelize = createSequelizeTypes(); + const fakeApp = { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + }; + }, + }, + }; + + return require('../../../app/model/order_items')(fakeApp); +} + +/** + * 构造工厂测试所需的最小应用对象。 + * @param {Object} [queryInterfaceOverrides={}] 查询接口覆盖项。 + * @return {Object} 最小应用对象。 + */ +function createFactoryApp(queryInterfaceOverrides = {}) { + const orderItemsModel = createOrderItemsModel(); + + return { + Sequelize: createSequelizeTypes(), + model: { + OrderItems: orderItemsModel, + define(name, attributes, options) { + return { + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => {}, + hasMany() {}, + belongsTo() {}, + }; + }, + getQueryInterface() { + return { + describeTable: async () => ({}), + showIndex: async () => [], + ...queryInterfaceOverrides, + }; + }, + query: async () => [[]], + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + _shardWarehouseIdsValidated: new Set(), + }; +} + +/** + * 将属性定义转换为 describeTable 兼容结果。 + * @param {Object} attributes 属性定义。 + * @return {Object} describeTable 兼容结果。 + */ +function buildDescribeTableResult(attributes) { + return Object.entries(attributes).reduce((result, [ columnName, attribute ]) => { + result[columnName] = { + type: attribute.type && typeof attribute.type.toSql === 'function' + ? attribute.type.toSql() + : String(attribute.type || ''), + allowNull: attribute.allowNull !== false, + }; + + if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) { + result[columnName].defaultValue = attribute.defaultValue; + } + + return result; + }, {}); +} + +/** + * 将索引定义转换为 showIndex 兼容结果。 + * @param {Array} indexes 索引定义。 + * @return {Array} showIndex 兼容结果。 + */ +function buildShowIndexResult(indexes) { + return indexes.map(index => ({ + Key_name: index.name, + unique: Boolean(index.unique), + nonUnique: index.unique ? 0 : 1, + fields: Array.isArray(index.fields) + ? index.fields.map(field => { + if (typeof field === 'string') { + return { + attribute: field, + }; + } + + return { + attribute: field.attribute || field.name || field.field || field.columnName, + length: field.length, + }; + }) + : [], + })); +} + +describe('test/app/model/order_items_factory.test.js', () => { + afterEach(() => { + mm.restore(); + }); + + it('should keep schema in sync when current table matches the model', async () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const tableAttributes = factory.getTableAttributes('current'); + const describeTableResult = buildDescribeTableResult(tableAttributes); + const showIndexResult = buildShowIndexResult(factory.generateIndexes(100000)); + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + + assert.equal(await factory.needsTableSchemaSync('wms_order_items_100000', 'current', 100000, true), false); + }); + + it('should sync and cache dynamic model when schema is inconsistent', async () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const tableName = factory.generateTableName(100000, 'current'); + const describeTableResult = buildDescribeTableResult(factory.getTableAttributes('current')); + const showIndexResult = buildShowIndexResult(factory.generateIndexes(100000)); + delete describeTableResult.item_code; + + let syncCalls = 0; + + mm(factory, 'checkTableExists', async () => true); + mm(factory.app.model, 'getQueryInterface', () => ({ + describeTable: async () => describeTableResult, + showIndex: async () => showIndexResult, + })); + mm(factory.app.model, 'define', (name, attributes, options) => ({ + name, + tableName: options.tableName, + rawAttributes: attributes, + sync: async () => { + syncCalls += 1; + }, + hasMany() {}, + belongsTo() {}, + })); + + const model = await factory.getOrCreateModel(100000, 'current'); + + assert.equal(model.tableName, tableName); + assert.equal(syncCalls, 1); + assert.strictEqual(await factory.getOrCreateModel(100000, 'current'), model); + assert.equal(syncCalls, 1); + }); + + it('should clear model cache and shard validation cache together', () => { + const factory = createOrderItemsFactory(createFactoryApp()); + factory.modelCache.set('100000_current', {}); + factory.creatingTables.set('100000_current', Promise.resolve()); + factory.app._shardWarehouseIdsValidated.add('100000'); + + factory.clearCache(100000, 'current'); + + assert.equal(factory.modelCache.has('100000_current'), false); + assert.equal(factory.creatingTables.has('100000_current'), false); + assert.equal(factory.app._shardWarehouseIdsValidated.size, 0); + }); + + it('should add archive_time to history attributes', () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const historyAttributes = factory.getTableAttributes('history'); + + assert.ok(historyAttributes.archive_time); + assert.equal(typeof historyAttributes.archive_time.type.toSql, 'function'); + }); + + it('should expose new order item snapshot fields in table attributes and indexes', () => { + const factory = createOrderItemsFactory(createFactoryApp()); + const currentAttributes = factory.getTableAttributes('current'); + const indexes = factory.generateIndexes(100000); + + assert.ok(currentAttributes.item_snapshot, '应包含 item_snapshot 字段'); + assert.equal(currentAttributes.storage_id, undefined, '不应包含 storage_id 字段'); + assert.equal(currentAttributes.space_id, undefined, '不应包含 space_id 字段'); + assert.equal(currentAttributes.stock_snapshot, undefined, '不应包含 stock_snapshot 字段'); + assert.equal(indexes.some(index => index.name === 'idx_100000_storage_id'), false); + assert.equal(indexes.some(index => index.name === 'idx_100000_space_id'), false); + }); + + it('should create and cache dispatch model with dispatch table name', async () => { + const factory = createOrderItemsFactory(createFactoryApp()); + + const model = await factory.getOrCreateModel(100000, 'dispatch'); + + assert.equal(model.tableName, 'wms_order_items_100000_dispatch'); + assert.strictEqual(await factory.getOrCreateModel(100000, 'dispatch'), model); + }); +}); diff --git a/test/app/model/picking.test.js b/test/app/model/picking.test.js new file mode 100644 index 0000000..fd7eeb3 --- /dev/null +++ b/test/app/model/picking.test.js @@ -0,0 +1,80 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +function createSequelizeTypes() { + const makeType = sql => ({ + toSql() { + return sql; + }, + }); + + const unsignedBigInt = length => { + const type = makeType(`BIGINT(${length})`); + type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`); + return type; + }; + + return { + BIGINT: unsignedBigInt, + STRING: length => makeType(`VARCHAR(${length})`), + INTEGER: length => { + const type = makeType(`INT(${length})`); + type.UNSIGNED = makeType(`INT(${length}) UNSIGNED`); + return type; + }, + DATE: makeType('DATETIME'), + literal(value) { + return { + toSql() { + return value; + }, + }; + }, + }; +} + +function createApp() { + const Sequelize = createSequelizeTypes(); + + return { + Sequelize, + model: { + define(name, attributes, options) { + return { + name, + rawAttributes: attributes, + options, + belongsTo() {}, + }; + }, + }, + }; +} + +describe('test/app/model/picking.test.js', () => { + it('should define wms_picking fields and indexes', () => { + const app = createApp(); + const Picking = require('../../../app/model/picking')(app); + + assert.equal(Picking.options.tableName, 'wms_picking'); + assert.equal(Picking.options.comment, '订单储位分配表'); + assert.ok(Picking.rawAttributes.order_id); + assert.ok(Picking.rawAttributes.order_item_id); + assert.ok(Picking.rawAttributes.storage_id); + assert.ok(Picking.rawAttributes.quantity); + assert.ok(Picking.rawAttributes.space_id); + assert.ok(Picking.rawAttributes.space_name); + assert.ok(Picking.rawAttributes.status); + assert.equal(Picking.rawAttributes.status.defaultValue, 'pending'); + assert.equal(Picking.rawAttributes.quantity.defaultValue, 1); + + const indexNames = (Picking.options.indexes || []).map(index => index.name); + assert.ok(indexNames.includes('idx_wms_picking_order_id')); + assert.ok(indexNames.includes('idx_wms_picking_order_item_id')); + assert.ok(indexNames.includes('idx_wms_picking_storage_id')); + assert.ok(indexNames.includes('idx_wms_picking_space_id')); + assert.ok(indexNames.includes('idx_wms_picking_status')); + assert.ok(indexNames.includes('idx_wms_picking_order_item_space')); + }); +}); \ No newline at end of file diff --git a/test/app/schedule/notice_stock_remaining.test.js b/test/app/schedule/notice_stock_remaining.test.js new file mode 100644 index 0000000..3b642d5 --- /dev/null +++ b/test/app/schedule/notice_stock_remaining.test.js @@ -0,0 +1,448 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const schedule = require('../../../app/schedule/notice_stock_remaining'); + +const CACHE_KEY_PREFIX = 'notice_stock_remaining_notified'; +const LEGACY_CACHE_KEY = 'notice_stock_remaining_notified_list'; + +function createLogger() { + return { + info() {}, + warn() {}, + error() {}, + debug() {}, + }; +} + +function createSequelizeInstanceLikeRecord(values = {}, associations = {}) { + const dataValues = { ...values }; + const includedValues = { ...associations }; + const prototype = { + getDataValue(fieldName) { + if (Object.prototype.hasOwnProperty.call(dataValues, fieldName)) { + return dataValues[fieldName]; + } + + return includedValues[fieldName]; + }, + get(fieldName) { + return this.getDataValue(fieldName); + }, + }; + + for (const fieldName of Object.keys(dataValues)) { + Object.defineProperty(prototype, fieldName, { + enumerable: false, + configurable: true, + get() { + return dataValues[fieldName]; + }, + }); + } + + for (const fieldName of Object.keys(includedValues)) { + Object.defineProperty(prototype, fieldName, { + enumerable: false, + configurable: true, + get() { + return includedValues[fieldName]; + }, + }); + } + + return Object.create(prototype); +} + +function buildLocalDateKey(dateValue) { + const year = String(dateValue.getFullYear()); + const month = String(dateValue.getMonth() + 1).padStart(2, '0'); + const day = String(dateValue.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; +} + +async function withFixedDate(fixedDate, handler) { + const OriginalDate = Date; + const fixedTime = fixedDate.getTime(); + + class FixedDate extends OriginalDate { + constructor(...args) { + if (args.length === 0) { + super(fixedTime); + return; + } + + super(...args); + } + + static now() { + return fixedTime; + } + } + + Object.setPrototypeOf(FixedDate, OriginalDate); + FixedDate.parse = OriginalDate.parse.bind(OriginalDate); + FixedDate.UTC = OriginalDate.UTC.bind(OriginalDate); + + global.Date = FixedDate; + + try { + return await handler(); + } finally { + global.Date = OriginalDate; + } +} + +function createScheduleHarness(options = {}) { + const noticePayloads = []; + const cacheWrites = []; + const cacheStore = new Map(Object.entries(options.cacheStore || {})); + + const ctx = { + app: { + _noticeStockRemainingRunning: false, + Sequelize: { + Op: { + gt: Symbol('gt'), + in: Symbol('in'), + ne: Symbol('ne'), + lte: Symbol('lte'), + }, + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + async setCacheAsync(cacheKey, data, ttl) { + cacheWrites.push({ cacheKey, data, ttl }); + cacheStore.set(cacheKey, data); + }, + formatDate(dateValue) { + return dateValue.toISOString(); + }, + }, + logger: createLogger(), + model: { + StockWarehouse: { + async findAll() { + return options.stockRows || []; + }, + }, + Storage: { + async findAll() { + return options.storageRows || []; + }, + }, + LocationSpace: {}, + }, + service: { + systems: { + notice: { + async send(payload) { + noticePayloads.push(payload); + if (typeof options.sendHandler === 'function') { + return await options.sendHandler(payload); + } + + return { + success: true, + }; + }, + }, + }, + }, + }; + + if (options.useNoticeIndexSend) { + delete ctx.service.systems.notice.send; + ctx.service.systems.notice.index = { + async send(payload) { + noticePayloads.push(payload); + if (typeof options.sendHandler === 'function') { + return await options.sendHandler(payload); + } + + return { + success: true, + }; + }, + }; + } + + return { + ctx, + noticePayloads, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/schedule/notice_stock_remaining.test.js', () => { + it('should ignore legacy global cache and write back stock-day cache keys', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({ + cacheStore: { + [LEGACY_CACHE_KEY]: [ 'stock:2001' ], + }, + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-01', + custom_name: '一号位', + }, + }, + { + id: 9002, + stock_id: 2001, + batch_no: 'BATCH-2', + warehouse_id: 20, + store_id: 10, + quantity: 8, + available_quantity: 8, + expiry_date: new Date(2026, 3, 17, 9, 0, 0), + inbound_time: new Date(2026, 3, 12, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-02', + custom_name: '二号位', + }, + }, + ], + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + const dateKey = buildLocalDateKey(fixedDate); + const expectedCacheKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`; + + assert.equal(noticePayloads.length, 1); + assert.equal(noticePayloads[0].businessId, 2001); + assert.equal(noticePayloads[0].metadata.businessId, 2001); + assert.equal(noticePayloads[0].metadata.stockId, 2001); + assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2001'); + assert.equal(noticePayloads[0].metadata.cacheKey, expectedCacheKey); + + assert.equal(cacheWrites.length, 1); + assert.equal(cacheWrites[0].cacheKey, expectedCacheKey); + assert.deepEqual(cacheWrites[0].data, { + notifiedAt: fixedDate.toISOString(), + stockId: 2001, + notifyKey: 'stock:2001', + }); + assert.equal(cacheWrites[0].ttl, 24 * 60 * 60); + + assert.equal(ctx.app._noticeStockRemainingRunning, false); + }); + + it('should keep same-day dedupe per stock without extending other stocks', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const dateKey = buildLocalDateKey(fixedDate); + const cachedStockKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`; + const otherStockKey = `${CACHE_KEY_PREFIX}:stock:2002:${dateKey}`; + const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({ + cacheStore: { + [cachedStockKey]: { + notifiedAt: fixedDate.toISOString(), + stockId: 2001, + notifyKey: 'stock:2001', + }, + }, + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + { + id: 2002, + item_code: 'SKU-2002', + item_name: '测试商品B', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + createSequelizeInstanceLikeRecord( + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + }, + { + space: createSequelizeInstanceLikeRecord({ + space_code: 'A-01', + custom_name: '一号位', + }), + } + ), + createSequelizeInstanceLikeRecord( + { + id: 9002, + stock_id: 2002, + batch_no: 'BATCH-2', + warehouse_id: 20, + store_id: 10, + quantity: 6, + available_quantity: 6, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + }, + { + space: createSequelizeInstanceLikeRecord({ + space_code: 'B-01', + custom_name: '二号位', + }), + } + ), + ], + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + assert.equal(noticePayloads.length, 1); + assert.equal(noticePayloads[0].businessId, 2002); + assert.equal(noticePayloads[0].metadata.stockId, 2002); + assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2002'); + assert.equal(noticePayloads[0].metadata.cacheKey, otherStockKey); + + assert.equal(cacheWrites.length, 1); + assert.equal(cacheWrites[0].cacheKey, otherStockKey); + assert.equal(ctx.app._noticeStockRemainingRunning, false); + }); + + it('should keep retrying when notice send reports failure', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const { ctx, noticePayloads, cacheWrites } = createScheduleHarness({ + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-01', + custom_name: '一号位', + }, + }, + ], + sendHandler() { + return { + success: false, + }; + }, + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + const dateKey = buildLocalDateKey(fixedDate); + const expectedCacheKey = `${CACHE_KEY_PREFIX}:stock:2001:${dateKey}`; + + assert.equal(noticePayloads.length, 1); + assert.equal(cacheWrites.length, 0); + assert.equal(ctx.app._noticeStockRemainingRunning, false); + assert.equal(noticePayloads[0].metadata.cacheKey, expectedCacheKey); + }); + + it('should fallback to notice.index.send when notice.send is missing', async () => { + const fixedDate = new Date(2026, 3, 14, 9, 0, 0); + const { ctx, noticePayloads } = createScheduleHarness({ + useNoticeIndexSend: true, + stockRows: [ + { + id: 2001, + item_code: 'SKU-2001', + item_name: '测试商品A', + store_id: 10, + warehouse_id: 20, + remaining_threshold_days: 7, + }, + ], + storageRows: [ + { + id: 9001, + stock_id: 2001, + batch_no: 'BATCH-1', + warehouse_id: 20, + store_id: 10, + quantity: 5, + available_quantity: 5, + expiry_date: new Date(2026, 3, 16, 9, 0, 0), + inbound_time: new Date(2026, 3, 13, 9, 0, 0), + is_enabled: 1, + delete_at: null, + space: { + space_code: 'A-01', + custom_name: '一号位', + }, + }, + ], + }); + + await withFixedDate(fixedDate, async () => { + await schedule.task(ctx); + }); + + assert.equal(noticePayloads.length, 1); + assert.equal(noticePayloads[0].businessId, 2001); + assert.equal(noticePayloads[0].metadata.notifyKey, 'stock:2001'); + assert.equal(ctx.app._noticeStockRemainingRunning, false); + }); +}); diff --git a/test/app/schedule/sync_outbound_orders_to_delivery.test.js b/test/app/schedule/sync_outbound_orders_to_delivery.test.js new file mode 100644 index 0000000..82de6df --- /dev/null +++ b/test/app/schedule/sync_outbound_orders_to_delivery.test.js @@ -0,0 +1,47 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const schedule = require('../../../app/schedule/sync_outbound_orders_to_delivery'); + +describe('test/app/schedule/sync_outbound_orders_to_delivery.test.js', () => { + it('should run every 1 minute in worker mode and avoid reentry', async () => { + assert.equal(schedule.schedule.interval, '1m'); + assert.equal(schedule.schedule.type, 'worker'); + assert.equal(schedule.schedule.immediate, false); + assert.equal(schedule.queryTimeoutMs, 15000); + assert.equal(schedule.executionTimeoutMs, 30000); + + let invokeCount = 0; + const ctx = { + app: { + _syncOutboundOrdersToDeliveryRunning: false, + }, + logger: { + info() {}, + error() {}, + }, + service: { + systems: { + orderDeliveryMigration: { + async syncOutboundOrdersToDelivery(data) { + invokeCount += 1; + assert.equal(data.queryTimeoutMs, 15000); + assert.equal(data.executionTimeoutMs, 30000); + return { + totalCreated: 1, + }; + }, + }, + }, + }, + }; + + await schedule.task(ctx); + assert.equal(invokeCount, 1); + assert.equal(ctx.app._syncOutboundOrdersToDeliveryRunning, false); + + ctx.app._syncOutboundOrdersToDeliveryRunning = true; + await schedule.task(ctx); + assert.equal(invokeCount, 1); + }); +}); diff --git a/test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js b/test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js new file mode 100644 index 0000000..3c257d8 --- /dev/null +++ b/test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js @@ -0,0 +1,48 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const schedule = require('../../../app/schedule/sync_outbound_timeout_orders_to_delivery'); + +describe('test/app/schedule/sync_outbound_timeout_orders_to_delivery.test.js', () => { + it('should run every 10 minutes in worker mode and avoid reentry', async () => { + assert.equal(schedule.schedule.interval, '10m'); + assert.equal(schedule.schedule.type, 'worker'); + assert.equal(schedule.schedule.immediate, false); + assert.equal(schedule.queryTimeoutMs, 120000); + assert.equal(schedule.executionTimeoutMs, 300000); + + let invokeCount = 0; + const ctx = { + app: { + _syncTimeoutOutboundOrdersToDeliveryRunning: false, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + orderDeliveryMigration: { + async retryTimeoutOutboundOrdersToDelivery(data) { + invokeCount += 1; + assert.equal(data.queryTimeoutMs, 120000); + assert.equal(data.executionTimeoutMs, 300000); + return { + totalCreated: 1, + }; + }, + }, + }, + }, + }; + + await schedule.task(ctx); + assert.equal(invokeCount, 1); + assert.equal(ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning, false); + + ctx.app._syncTimeoutOutboundOrdersToDeliveryRunning = true; + await schedule.task(ctx); + assert.equal(invokeCount, 1); + }); +}); diff --git a/test/app/service/qimenMethods/order.test.js b/test/app/service/qimenMethods/order.test.js new file mode 100644 index 0000000..b12da0e --- /dev/null +++ b/test/app/service/qimenMethods/order.test.js @@ -0,0 +1,216 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const OrderService = require('../../../../app/service/qimenMethods/order'); + +function createHarness(options = {}) { + const calls = { + findOne: 0, + update: 0, + commit: 0, + rollback: 0, + noticeSend: 0, + }; + + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + calls.commit += 1; + }, + async rollback() { + calls.rollback += 1; + }, + }; + + const existingOrder = options.existingOrder === undefined ? { + id: 1, + pick_status: 'none', + print_status: 'none', + async update(values) { + calls.update += 1; + calls.updateValues = values; + Object.assign(this, values); + }, + } : options.existingOrder; + + const ctx = { + app: { + config: {}, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + notice: { + async send(payload) { + calls.noticeSend += 1; + calls.noticePayload = payload; + return { + success: true, + }; + }, + }, + }, + }, + model: { + async transaction() { + calls.transaction = true; + return transaction; + }, + OrderExpress: { + async findAll(query) { + calls.orderExpressFindAll = query; + if (options.orderExpress === undefined) { + return []; + } + return Array.isArray(options.orderExpress) ? options.orderExpress : [ options.orderExpress ]; + }, + }, + EntryOrder: { + async findOne(query) { + calls.findOne += 1; + calls.findOneQuery = query; + return options.existingOrder === null ? null : existingOrder; + }, + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findOne(query) { + calls.findOne += 1; + calls.findOneQuery = query; + return options.existingOrder === null ? null : existingOrder; + }, + }; + }, + }, + }, + }; + + const service = new OrderService(ctx); + service.setInfo(options.storeId || 1000000, options.warehouseId || 100000, 'app-key', 'customer-id', 'warehouse-code'); + + return { + service, + calls, + transaction, + existingOrder, + }; +} + +describe('test/app/service/qimenMethods/order.test.js', () => { + it('should cancel order directly when pick_status and print_status are none', async () => { + const { service, calls, existingOrder } = createHarness(); + + const result = await service.cancel({ + request: { + orderType: 'JYCK', + orderCode: 'OD-001', + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消订单成功'); + assert.equal(calls.findOne, 1); + assert.equal(calls.commit, 1); + assert.equal(calls.rollback, 0); + assert.equal(calls.update, 1); + assert.equal(calls.updateValues.status, 'cancel'); + assert.equal(calls.updateValues.outbound_status, 'fin'); + assert.equal(calls.updateValues.step, 4); + assert.equal(calls.noticeSend, 0); + assert.equal(existingOrder.status, 'cancel'); + assert.equal(existingOrder.outbound_status, 'fin'); + assert.equal(existingOrder.step, 4); + }); + + it('should switch to intercepting when pick_status or print_status is not none', async () => { + const { service, calls, existingOrder } = createHarness({ + existingOrder: { + id: 2, + pick_status: 'fin', + print_status: 'none', + async update(values) { + calls.update += 1; + calls.updateValues = values; + Object.assign(this, values); + }, + }, + orderExpress: [ + { + waybill_code: 'WB-002', + logistics_code: 'STO', + logistics_name: '申通', + logistics_interface_id: 66, + }, + { + waybill_code: 'WB-001', + logistics_code: 'YTO', + logistics_name: '圆通', + logistics_interface_id: 88, + }, + ], + }); + + const result = await service.cancel({ + request: { + orderType: 'JYCK', + orderCode: 'OD-002', + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '取消失败,已通知拦截执行'); + assert.equal(calls.findOne, 1); + assert.equal(calls.commit, 1); + assert.equal(calls.rollback, 0); + assert.equal(calls.update, 1); + assert.equal(calls.updateValues.intercept_status, 'intercepting'); + assert.equal(calls.noticeSend, 1); + assert.equal(calls.noticePayload.event, 'order_cancel_intercepted'); + assert.equal(calls.noticePayload.businessName, 'order'); + assert.equal(calls.noticePayload.messageType, 'text'); + assert.deepEqual(calls.noticePayload.metadata.express, [ + { + waybill_code: 'WB-002', + logistics_code: 'STO', + logistics_name: '申通', + logistics_interface_id: 66, + }, + { + waybill_code: 'WB-001', + logistics_code: 'YTO', + logistics_name: '圆通', + logistics_interface_id: 88, + }, + ]); + assert.equal(calls.orderExpressFindAll.where.order_id, 2); + assert.equal(existingOrder.intercept_status, 'intercepting'); + }); + + it('should rollback when the order cannot be found', async () => { + const { service, calls } = createHarness({ + existingOrder: null, + }); + + const result = await service.cancel({ + request: { + orderType: 'JYCK', + orderCode: 'OD-404', + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '未找到对应的订单'); + assert.equal(calls.findOne, 1); + assert.equal(calls.commit, 0); + assert.equal(calls.rollback, 1); + assert.equal(calls.update, 0); + assert.equal(calls.noticeSend, 0); + }); +}); \ No newline at end of file diff --git a/test/app/service/systemMethods/order.base.step.test.js b/test/app/service/systemMethods/order.base.step.test.js index 3f4e5b3..ce278a7 100644 --- a/test/app/service/systemMethods/order.base.step.test.js +++ b/test/app/service/systemMethods/order.base.step.test.js @@ -2,26 +2,203 @@ const assert = require('node:assert/strict'); const Sequelize = require('sequelize'); +const OrderIndexService = require('../../../../app/service/systemMethods/order/index'); const OrderBaseService = require('../../../../app/service/systemMethods/order/base'); +const { buildRows, createOrderHarness, matchesWhere } = require('../../../support/order_service_test_helper'); describe('test/app/service/systemMethods/order.base.step.test.js', () => { - function createService() { + function createService(storeId = 100000) { const ctx = { app: { Sequelize, config: {}, }, - user: {}, + user: { + store_id: storeId, + }, }; return new OrderBaseService(ctx); } - it('should build where with step equality filter', () => { - const service = createService(); - const where = service.buildWhere({ step: 1 }, 100000); + function createRecordModel(rows, capture) { + const normalizedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; - assert.equal(where.warehouse_id, 100000); + return { + async findOne(options = {}) { + capture.findOneOptions = options; + const matchedRow = normalizedRows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + async findAll(options = {}) { + capture.findAllOptions = options; + return normalizedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; + } + + function createDetailHarness(options = {}) { + const storeId = options.storeId || 100000; + const orderRowsByType = options.orderRowsByType || {}; + const itemRowsByType = options.itemRowsByType || {}; + const expressRowsByOrderId = options.expressRowsByOrderId || {}; + const captures = { + orderFactoryCalls: [], + itemFactoryCalls: [], + expressQueries: [], + }; + + const ctx = { + app: { + Sequelize, + config: {}, + }, + user: { + store_id: storeId, + }, + model: { + OrderDeliveryFactory: { + async getCurrentModel(warehouseId) { + const capture = { + method: 'getCurrentModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.current || [], capture); + }, + async getHistoryModel(warehouseId) { + const capture = { + method: 'getHistoryModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.history || [], capture); + }, + async getDispatchModel(warehouseId) { + const capture = { + method: 'getDispatchModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.dispatch || [], capture); + }, + async getOutsourcedModel(warehouseId) { + const capture = { + method: 'getOutsourcedModel', + warehouseId, + }; + captures.orderFactoryCalls.push(capture); + return createRecordModel(orderRowsByType.outsourced || [], capture); + }, + }, + OrderItemsFactory: { + async getCurrentModel(warehouseId) { + const capture = { + method: 'getCurrentModel', + warehouseId, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType.current || [], capture); + }, + async getHistoryModel(warehouseId) { + const capture = { + method: 'getHistoryModel', + warehouseId, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType.history || [], capture); + }, + async getDispatchModel(warehouseId) { + const capture = { + method: 'getDispatchModel', + warehouseId, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType.dispatch || [], capture); + }, + async getOrCreateModel(warehouseId, type) { + const capture = { + method: 'getOrCreateModel', + warehouseId, + type, + }; + captures.itemFactoryCalls.push(capture); + return createRecordModel(itemRowsByType[type] || [], capture); + }, + }, + OrderExpress: { + async findAll(options = {}) { + captures.expressQueries.push(options); + const orderId = Number(options?.where?.order_id || 0); + return (expressRowsByOrderId[orderId] || []).map(row => ({ ...row })); + }, + }, + }, + }; + + return { + service: new OrderIndexService(ctx), + ctx, + captures, + }; + } + + function createAuthService(userOverrides = {}) { + const ctx = { + header: { + platform: 'web', + project: 'all', + }, + set() {}, + app: { + config: { + jwt: { + secret: 'test-secret', + expiresIn: '3600', + }, + }, + jwt: { + verify() { + return { + id: 1, + exp: Math.floor(Date.now() / 1000) + 3600, + }; + }, + sign() { + return 'refreshed-token'; + }, + }, + }, + service: { + systems: { + auth: { + user: { + async findById() { + return { + id: 1, + username: 'tester', + status: 1, + auth_end: '2099-12-31 23:59:59', + permissions: [], + ...userOverrides, + }; + }, + }, + }, + }, + }, + }; + + return new OrderIndexService(ctx); + } + + it('should inject current store_id into buildWhere', () => { + const service = createService(100001); + const where = service.buildWhere({ step: 1 }); + + assert.equal(where.warehouse_id, 100001); assert.equal(where.step, 1); assert.equal(Object.prototype.hasOwnProperty.call(where, 'audit_status'), false); }); @@ -33,11 +210,372 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => { operator: 'in', value: [ 0, 1, 2 ], }, - }, 100000); + }); assert.equal(where.warehouse_id, 100000); assert.deepEqual(where.step, { [Sequelize.Op.in]: [ 0, 1, 2 ], }); }); + + it('should reject warehouse fields in buildWhere input', () => { + const service = createService(); + + assert.throws(() => { + service.buildWhere({ + warehouse_id: 100000, + }); + }, /禁止传入 warehouse_id \/ warehouseId/); + + assert.throws(() => { + service.buildWhere({ + warehouseId: 100000, + }); + }, /禁止传入 warehouse_id \/ warehouseId/); + }); + + it('should cap pageSize and keep deliveryOrder step filter in listByModule', async () => { + const rows = buildRows(250, index => ({ + step: index < 230 ? 1 : 2, + dispatch_lane: 'm4', + })); + const { service, captures } = createOrderHarness(OrderBaseService, { + rowsByModule: { + deliveryOrder: rows, + }, + }); + + const result = await service.listByModule('deliveryOrder', { + pagination: { + page: 1, + pageSize: 999, + }, + where: { + step: 1, + }, + }); + + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 200); + assert.equal(result.pagination.total, 230); + assert.equal(result.list.length, 200); + assert.ok(result.list.every(item => item.step === 1)); + assert.equal(captures[0].moduleName, 'deliveryOrder'); + assert.equal(captures[0].findOptions.limit, 200); + assert.equal(captures[0].findOptions.offset, 0); + }); + + it('should use current store_id in listByModule and reject warehouse bypass fields', async () => { + const rows = buildRows(6, () => ({ + warehouse_id: 100001, + step: 1, + })); + const { service, captures } = createOrderHarness(OrderBaseService, { + storeId: 100001, + rowsByModule: { + order: rows, + }, + }); + + const result = await service.listByModule('order', { + pagination: { + page: 1, + pageSize: 10, + }, + where: { + step: 1, + }, + }); + + assert.equal(result.pagination.total, 6); + assert.equal(captures[0].countWhere.warehouse_id, 100001); + assert.equal(captures[0].findOptions.where.warehouse_id, 100001); + assert.ok(result.list.every(item => item.warehouse_id === 100001)); + + await assert.rejects(() => service.listByModule('order', { + where: { + warehouse_id: 100001, + }, + }), /禁止传入 warehouse_id \/ warehouseId/); + }); + + it('should keep pendingOrder hidden for padding rows while outboundOrder still exposes none and padding', async () => { + const { service } = createOrderHarness(OrderBaseService, { + rowsByModule: { + pendingOrder: [ + { + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100000, + step: 2, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 3, + warehouse_id: 100000, + step: 1, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 4, + warehouse_id: 100001, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + outboundOrder: [ + { + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100000, + step: 2, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 3, + warehouse_id: 100000, + step: 1, + outbound_status: 'padding', + updated_at: '2026-04-12 00:00:00', + }, + { + id: 4, + warehouse_id: 100001, + step: 1, + outbound_status: 'none', + updated_at: '2026-04-12 00:00:00', + }, + ], + }, + }); + + const pendingResult = await service.listByModule('pendingOrder', {}); + const outboundResult = await service.listByModule('outboundOrder', {}); + + assert.deepEqual(pendingResult.list.map(item => item.id), [ 1 ]); + assert.ok(pendingResult.list.every(item => item.outbound_status !== 'padding')); + assert.deepEqual(outboundResult.list.map(item => item.id), [ 1, 2, 3 ]); + assert.ok(outboundResult.list.some(item => item.outbound_status === 'padding')); + assert.ok(outboundResult.list.some(item => item.outbound_status === 'none')); + assert.ok(outboundResult.list.every(item => item.warehouse_id === 100000)); + }); + + it('should attach express numbers and normalize sys names in all order lists', async () => { + const rows = buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + sys_platform_name: index === 0 ? '淘宝' : null, + sys_logistics_name: index === 0 ? '申通' : undefined, + })); + const { service } = createOrderHarness(OrderBaseService, { + rowsByModule: { + order: rows, + }, + }); + + service.ctx.model = { + OrderExpress: { + async findAll({ where }) { + const orderIds = Array.isArray(where && where.order_id && where.order_id[Sequelize.Op.in]) + ? where.order_id[Sequelize.Op.in] + : []; + + return orderIds.flatMap(orderId => { + if (Number(orderId) === 1) { + return [ + { + id: 11, + order_id: 1, + waybill_code: 'WB-001', + }, + { + id: 12, + order_id: 1, + waybill_code: 'WB-002', + }, + ]; + } + + if (Number(orderId) === 2) { + return [ + { + id: 21, + order_id: 2, + waybill_code: 'WB-003', + }, + ]; + } + + return []; + }); + }, + }, + }; + + const result = await service.listByModule('order', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }); + + assert.deepEqual(result.list[0].express_numbers, [ 'WB-001', 'WB-002' ]); + assert.deepEqual(result.list[0].waybill_codes, [ 'WB-001', 'WB-002' ]); + assert.deepEqual(result.list[1].express_numbers, [ 'WB-003' ]); + assert.deepEqual(result.list[1].waybill_codes, [ 'WB-003' ]); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'sys_platform_name'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'sys_logistics_name'), true); + assert.equal(result.list[0].sys_platform_name, '淘宝'); + assert.equal(result.list[0].sys_logistics_name, '申通'); + assert.equal(result.list[1].sys_platform_name, null); + assert.equal(result.list[1].sys_logistics_name, null); + }); + + it('should query detail by tableType and return orderItems, items, expresses and waybill_codes', async () => { + const { service, captures } = createDetailHarness({ + storeId: 100001, + orderRowsByType: { + history: [ + { + id: 501, + warehouse_id: 100001, + delivery_order_code: 'HIS-501', + step: 2, + }, + ], + }, + itemRowsByType: { + history: [ + { + id: 11, + order_id: 501, + item_code: 'SKU-001', + plan_qty: 2, + }, + { + id: 12, + order_id: 501, + item_code: 'SKU-002', + plan_qty: 1, + }, + ], + }, + expressRowsByOrderId: { + 501: [ + { + waybill_code: 'WB-501-A', + logistics_code: 'LC-A', + logistics_name: '物流A', + logistics_interface_id: '88', + }, + { + waybill_code: 'WB-501-B', + logistics_code: 'LC-B', + logistics_name: '物流B', + logistics_interface_id: 99, + }, + ], + }, + }); + + const result = await service.detail({ + id: 501, + tableType: 'history', + }); + + assert.equal(captures.orderFactoryCalls[0].method, 'getHistoryModel'); + assert.equal(captures.orderFactoryCalls[0].warehouseId, 100001); + assert.equal(captures.itemFactoryCalls[0].method, 'getHistoryModel'); + assert.equal(captures.itemFactoryCalls[0].warehouseId, 100001); + assert.equal(captures.expressQueries[0].where.order_id, 501); + assert.deepEqual(result.order, { + id: 501, + warehouse_id: 100001, + delivery_order_code: 'HIS-501', + step: 2, + }); + assert.strictEqual(result.order, result.detail); + assert.deepEqual(result.orderItems, [ + { + id: 11, + order_id: 501, + item_code: 'SKU-001', + plan_qty: 2, + }, + { + id: 12, + order_id: 501, + item_code: 'SKU-002', + plan_qty: 1, + }, + ]); + assert.deepEqual(result.items, result.orderItems); + assert.deepEqual(result.expresses, [ + { + waybill_code: 'WB-501-A', + logistics_code: 'LC-A', + logistics_name: '物流A', + logistics_interface_id: 88, + }, + { + waybill_code: 'WB-501-B', + logistics_code: 'LC-B', + logistics_name: '物流B', + logistics_interface_id: 99, + }, + ]); + assert.deepEqual(result.waybill_codes, [ 'WB-501-A', 'WB-501-B' ]); + }); + + it('should use current store_id as isolation condition in detail lookup', async () => { + const { service, captures } = createDetailHarness({ + storeId: 100002, + orderRowsByType: { + current: [ + { + id: 601, + warehouse_id: 100001, + delivery_order_code: 'CUR-601', + step: 1, + }, + ], + }, + }); + + await assert.rejects(() => service.detail({ + id: 601, + tableType: 'current', + }), /订单不存在或不属于当前仓库/); + + assert.equal(captures.orderFactoryCalls[0].method, 'getCurrentModel'); + assert.equal(captures.orderFactoryCalls[0].findOneOptions.where.warehouse_id, 100002); + assert.equal(captures.itemFactoryCalls.length, 0); + assert.equal(captures.expressQueries.length, 0); + }); + + it('should allow detail in the order permission white list', async () => { + const service = createAuthService(); + + const result = await service.checkAuth('order', 'detail', 'Bearer test-token'); + + assert.equal(result.status, 200); + assert.equal(result.message, 'ok'); + }); }); diff --git a/test/app/service/systemMethods/order/storageAllocation.test.js b/test/app/service/systemMethods/order/storageAllocation.test.js new file mode 100644 index 0000000..ae97548 --- /dev/null +++ b/test/app/service/systemMethods/order/storageAllocation.test.js @@ -0,0 +1,63 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageAllocationMethodService = require('../../../../../app/service/systemMethods/order/storageAllocation'); + +/** + * 创建系统方法测试上下文。 + * + * @return {{ ctx: Object, capture: Object }} 测试上下文。 + */ +function createHarness() { + const capture = { + request: null, + }; + + const ctx = { + app: {}, + service: { + systems: { + orderStorageAllocation: { + async allocateStorage(request) { + capture.request = request; + return { + code: 200, + message: '储位分配完成', + data: { + ok: true, + }, + }; + }, + }, + }, + }, + }; + + return { + ctx, + capture, + }; +} + +describe('test/app/service/systemMethods/order/storageAllocation.test.js', () => { + it('should normalize allocation input before delegating to the public service', async () => { + const { ctx, capture } = createHarness(); + const service = new StorageAllocationMethodService(ctx); + + const result = await service.allocateStorage({ + allowStorageLocation: true, + ids: '1,2,3', + warehouseId: 100000, + }); + + assert.deepEqual(capture.request, { + allow_storage_location: true, + order_ids: '1,2,3', + warehouse_id: 100000, + }); + assert.equal(result.flag, 'success'); + assert.equal(result.message, '储位分配完成'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, { ok: true }); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/delivery_order.auditStatus.test.js b/test/app/service/systems/delivery_order.auditStatus.test.js index d14d89a..5c4732b 100644 --- a/test/app/service/systems/delivery_order.auditStatus.test.js +++ b/test/app/service/systems/delivery_order.auditStatus.test.js @@ -6,6 +6,7 @@ const { app, mm } = require('egg-mock/bootstrap'); describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { let ctx; let deliveryOrderService; + let cacheStore; /** * Mock StoreWarehouse.findOne,兼容固定返回值或函数实现。 @@ -26,6 +27,12 @@ describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { beforeEach(() => { ctx = app.mockContext(); deliveryOrderService = ctx.service.systems.deliveryOrder; + cacheStore = new Map(); + + mm(app, 'getCacheAsync', async cacheKey => cacheStore.get(cacheKey)); + mm(app, 'setCacheAsync', async (cacheKey, value) => { + cacheStore.set(cacheKey, value); + }); }); afterEach(() => { @@ -78,12 +85,26 @@ describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { warehouseId: 100000, }; - // Mock platform check - mm(ctx.service.systems.platform, 'checkPlatformExists', async (platformCode, warehouseId) => { - if (platformCode === 'TAOBAO' && warehouseId === 100000) { - return { code: 'TAOBAO', name: '淘宝' }; - } - return null; + mm(ctx.service.systems.platform, 'getPlatformList', async () => ([ + { code: 'TAOBAO', name: '淘宝' }, + { code: 'TB', name: '淘宝默认' }, + ])); + mm(ctx.service.systems.express, 'getExpressList', async () => ([ + { code: 'STO', name: '申通' }, + ])); + mm(ctx, 'model', { + ...(ctx.model || {}), + Store: { + async findByPk() { + return { + id: 1000000, + subject_config: { + default_platform_code: 'TB', + default_express_code: 'STO', + }, + }; + }, + }, }); // 1. Test with step = 0 @@ -95,5 +116,65 @@ describe('test/app/service/systems/delivery_order.auditStatus.test.js', () => { const preparedDataApproved = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 1); assert.ok(preparedDataApproved, 'preparedDataApproved should not be null'); assert.equal(preparedDataApproved.step, 1, 'step should be 1'); + assert.equal(preparedDataApproved.source_platform_code, 'TAOBAO'); + assert.equal(preparedDataApproved.sys_platform_code, 'TAOBAO'); + }); + + it('should fallback invalid platform and logistics codes to cached store defaults without overwriting source fields', async () => { + const deliveryOrder = { + deliveryOrderCode: 'TEST_ORDER_002', + sourcePlatformCode: 'INVALID_PLATFORM', + sourcePlatformName: '外部平台', + logisticsCode: 'INVALID_EXPRESS', + logisticsName: '外部快递', + expressCode: 'YT', + receiverInfo: { name: 'test' }, + }; + const info = { + storeId: 1000000, + warehouseId: 100000, + }; + + let findByPkCallCount = 0; + mm(ctx, 'model', { + ...(ctx.model || {}), + Store: { + async findByPk() { + findByPkCallCount += 1; + return { + id: 1000000, + subject_config: { + default_platform_code: 'TB', + default_express_code: 'STO', + }, + }; + }, + }, + }); + mm(ctx.service.systems.platform, 'getPlatformList', async () => ([ + { code: 'TB', name: '淘宝' }, + { code: 'JD', name: '京东' }, + ])); + mm(ctx.service.systems.express, 'getExpressList', async () => ([ + { code: 'STO', name: '申通' }, + { code: 'YTO', name: '圆通' }, + ])); + + const firstPrepared = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 1); + const secondPrepared = await deliveryOrderService.prepareOrderData(deliveryOrder, info, 1); + + assert.equal(firstPrepared.source_platform_code, 'INVALID_PLATFORM'); + assert.equal(firstPrepared.source_platform_name, '外部平台'); + assert.equal(firstPrepared.sys_platform_code, 'TB'); + assert.equal(firstPrepared.sys_platform_name, '淘宝'); + assert.equal(firstPrepared.logistics_code, 'INVALID_EXPRESS'); + assert.equal(firstPrepared.logistics_name, '外部快递'); + assert.equal(firstPrepared.sys_logistics_code, 'STO'); + assert.equal(firstPrepared.sys_logistics_name, '申通'); + assert.equal(firstPrepared.express_code, 'YT'); + + assert.equal(secondPrepared.sys_platform_code, 'TB'); + assert.equal(secondPrepared.sys_logistics_code, 'STO'); + assert.equal(findByPkCallCount, 1, 'store subject_config should be loaded from cache on second call'); }); }); diff --git a/test/app/service/systems/delivery_order.oversell.test.js b/test/app/service/systems/delivery_order.oversell.test.js index 7c27cd6..c3fd5a3 100644 --- a/test/app/service/systems/delivery_order.oversell.test.js +++ b/test/app/service/systems/delivery_order.oversell.test.js @@ -76,6 +76,21 @@ function createHarness({ allowOversell }) { warehouse_code: 'WH-001', item_code: 'SKU-ZERO', item_name: '零库存商品', + goods_code: 'GOODS-ZERO', + sku_property: '颜色:黑', + stock_unit: '件', + gross_weight: 2, + net_weight: 1.5, + length: 10, + width: 20, + height: 30, + volume: 6000, + retail_price: 88.5, + barcode: 'BAR-ZERO', + brand_name: '测试品牌', + category_id: 9, + category_name: '测试分类', + item_type: 'normal', }; }, }, @@ -188,6 +203,33 @@ describe('test/app/service/systems/delivery_order.oversell.test.js', () => { assert.equal(result.stock_count, 1); assert.equal(result.item_total_count, 1); assert.equal(calls.bulkCreateArgs.rows.length, 1); + assert.equal(calls.bulkCreateArgs.rows[0].item_id, 1); + assert.equal(calls.bulkCreateArgs.rows[0].stock_id, 9001); + assert.deepEqual(calls.bulkCreateArgs.rows[0].item_snapshot, { + id: 1, + stock_id: 9001, + item_code: 'SKU-ZERO', + item_name: '零库存商品', + goods_code: 'GOODS-ZERO', + sku_property: '颜色:黑', + barcode: 'BAR-ZERO', + brand_name: '测试品牌', + category_id: 9, + category_name: '测试分类', + item_type: 'normal', + stock_unit: '件', + inventory_type: 'ZP', + retail_price: 88.5, + gross_weight: 2, + net_weight: 1.5, + length: 10, + width: 20, + height: 30, + volume: 6000, + }); + assert.equal(calls.bulkCreateArgs.rows[0].storage_id, undefined); + assert.equal(calls.bulkCreateArgs.rows[0].space_id, undefined); + assert.equal(calls.bulkCreateArgs.rows[0].stock_snapshot, undefined); assert.equal(stockWarehouseInstance.locked_quantity, 1); }); diff --git a/test/app/service/systems/excel.test.js b/test/app/service/systems/excel.test.js index 5e0e710..1dd247a 100644 --- a/test/app/service/systems/excel.test.js +++ b/test/app/service/systems/excel.test.js @@ -1,6 +1,9 @@ 'use strict'; const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); const XLSX = require('xlsx'); const ExcelService = require('../../../../app/service/systems/excel'); @@ -158,6 +161,48 @@ describe('test/app/service/systems/excel.test.js', () => { assert.equal(result.fileRecord.fileId, 9527); }); + it('should write files atomically without touching the target path directly', async () => { + const { service } = createService(); + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'wms-excel-')); + const targetPath = path.join(tempDir, '收货报表.xlsx'); + const writeCalls = []; + const originalWriteFile = fs.writeFile; + + fs.writeFile = async function patchedWriteFile(filePath, ...args) { + writeCalls.push(String(filePath)); + return originalWriteFile.call(this, filePath, ...args); + }; + + try { + await service.writeFile(targetPath, { + sheets: [ + { + name: '报表', + columns: [ + { header: '单号', key: 'order_no' }, + ], + rows: [ + { order_no: 'RK1001' }, + ], + }, + ], + }); + } finally { + fs.writeFile = originalWriteFile; + } + + assert.ok(writeCalls.length > 0); + assert.ok(writeCalls.every(filePath => filePath !== targetPath)); + + const buffer = await fs.readFile(targetPath); + assert.ok(buffer.length > 0); + + const workbook = XLSX.read(buffer, { type: 'buffer' }); + assert.deepEqual(workbook.SheetNames, [ '报表' ]); + + await fs.rm(tempDir, { recursive: true, force: true }); + }); + it('should honor skipHeader when object rows are used', async () => { const { service } = createService(); diff --git a/test/app/service/systems/express.test.js b/test/app/service/systems/express.test.js new file mode 100644 index 0000000..376613e --- /dev/null +++ b/test/app/service/systems/express.test.js @@ -0,0 +1,118 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ExpressService = require('../../../../app/service/systems/express'); +const IndexMethodService = require('../../../../app/service/systemMethods/index'); + +function createExpressServiceHarness(options = {}) { + const calls = { + findAll: 0, + getCache: 0, + setCache: 0, + }; + + const ctx = { + app: { + async getCacheAsync(cacheKey) { + calls.getCache += 1; + if (typeof options.getCacheAsync === 'function') { + return await options.getCacheAsync(cacheKey); + } + return options.cachedValue === undefined ? null : options.cachedValue; + }, + async setCacheAsync(cacheKey, value, ttl) { + calls.setCache += 1; + calls.cachePayload = { cacheKey, value, ttl }; + if (typeof options.setCacheAsync === 'function') { + return await options.setCacheAsync(cacheKey, value, ttl); + } + }, + }, + model: { + Express: { + async findAll(query) { + calls.findAll += 1; + calls.findAllQuery = query; + return options.rows || [ + { code: 'STO', name: '顺丰' }, + { code: 'TB', name: '淘宝快递' }, + ]; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/express.test.js', () => { + it('should load express list from database and cache it when cache is empty', async () => { + const { ctx, calls } = createExpressServiceHarness(); + const service = new ExpressService(ctx); + + const result = await service.getExpressList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.findAll, 1); + assert.equal(calls.setCache, 1); + assert.equal(calls.cachePayload.cacheKey, 'express:list'); + assert.equal(calls.cachePayload.ttl, 600); + assert.deepEqual(result, [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' }, + { code: 'TB', name: '淘宝快递', value: 'TB', label: '淘宝快递' }, + ]); + }); + + it('should return cached express list without querying database', async () => { + const cachedValue = [ + { code: 'SF', name: '顺丰', value: 'SF', label: '顺丰' }, + ]; + const { ctx, calls } = createExpressServiceHarness({ + cachedValue, + }); + const service = new ExpressService(ctx); + + const result = await service.getExpressList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.findAll, 0); + assert.equal(calls.setCache, 0); + assert.deepEqual(result, cachedValue); + }); + + it('should delegate index.getExpressList to the express service', async () => { + const { ctx } = createExpressServiceHarness(); + let serviceCalls = 0; + ctx.service = { + systems: { + express: { + async getExpressList() { + serviceCalls += 1; + return [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' }, + ]; + }, + }, + }, + }; + + const methodService = new IndexMethodService(ctx); + const result = await methodService.getExpressList(); + + assert.equal(serviceCalls, 1); + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, [ + { code: 'STO', name: '顺丰', value: 'STO', label: '顺丰' }, + ]); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/notice.test.js b/test/app/service/systems/notice.test.js index 8f46390..2707ef6 100644 --- a/test/app/service/systems/notice.test.js +++ b/test/app/service/systems/notice.test.js @@ -10,14 +10,14 @@ describe('test/app/service/systems/notice.test.js', () => { const webhookRows = [ { id: 1, - store_id: 1000000, + store_id: 100000, hook_type: 'custom', hook_url: 'https://example.com/webhook/a', events: [ 'receiving_completed' ], }, { id: 2, - store_id: 1000000, + store_id: 100000, hook_type: 'custom', hook_url: 'https://example.com/webhook/b', events: [ 'stock.low' ], @@ -31,7 +31,7 @@ describe('test/app/service/systems/notice.test.js', () => { model: { NotificationWebhook: { async findAll({ where }) { - assert.equal(Number(where.store_id), 1000000); + assert.equal(Number(where.store_id), 100000); assert.equal(Number(where.status), 1); return webhookRows; }, @@ -688,6 +688,7 @@ describe('test/app/service/systems/notice.test.js', () => { assert.ok(Array.isArray(availableEvents)); assert.ok(availableEvents.some(item => item.code === 'all')); assert.ok(availableEvents.some(item => item.code === 'receiving_completed')); + assert.ok(availableEvents.some(item => item.code === 'order_cancel_intercepted')); assert.doesNotThrow(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'all', 'receiving_completed' ])); assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'receiving.completed' ]), /不支持|非法/); assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ '1receiving_completed' ]), /不支持|非法/); diff --git a/test/app/service/systems/order_delivery_migration.test.js b/test/app/service/systems/order_delivery_migration.test.js new file mode 100644 index 0000000..aa4f11d --- /dev/null +++ b/test/app/service/systems/order_delivery_migration.test.js @@ -0,0 +1,695 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderDeliveryMigrationService = require('../../../../app/service/systems/order_delivery_migration'); +const { matchesWhere } = require('../../../support/order_service_test_helper'); + +function cloneRow(row) { + return { + ...(row || {}), + }; +} + +function buildOrderRows(count, overrides = {}) { + return Array.from({ length: count }, (_, index) => ({ + id: index + 1, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: `OD-${String(index + 1).padStart(5, '0')}`, + step: 4, + outbound_status: 'fin', + delivery_time: new Date('2026-04-12T00:00:00Z'), + updated_at: '2026-04-12 00:00:00', + ...overrides, + })); +} + +function buildItemRows(orderRows, overrides = {}) { + return (Array.isArray(orderRows) ? orderRows : []).map((orderRow, index) => ({ + id: index + 10001, + order_id: orderRow.id, + actual_price: 1.00, + retail_price: 2.00, + ext_code: `EXT-${String(index + 1).padStart(5, '0')}`, + inventory_type: 'default', + item_code: `ITEM-${String(index + 1).padStart(5, '0')}`, + item_id: index + 20001, + item_name: `商品-${String(index + 1).padStart(5, '0')}`, + order_line_no: `LINE-${String(index + 1).padStart(5, '0')}`, + owner_code: 'OWNER-001', + plan_qty: 1, + source_order_code: orderRow.delivery_order_code, + sub_source_order_code: null, + extend_props: { + source: 'migration-test', + }, + stock_id: index + 30001, + created_at: '2026-04-12 00:00:00', + updated_at: '2026-04-12 00:00:00', + ...overrides, + })); +} + +function buildDispatchKey(row) { + return [ row.delivery_order_code, row.store_id, row.warehouse_id ].join('::'); +} + +function buildRetryableDatabaseError(message, code = 1205) { + const error = new Error(message); + error.name = 'SequelizeDatabaseError'; + error.code = code; + error.parent = { + code, + errno: code, + }; + + return error; +} + +function createTransaction(calls) { + return { + committed: false, + rolledBack: false, + operations: [], + touchedModels: new Set(), + async commit() { + this.committed = true; + calls.commitCount += 1; + + for (const model of this.touchedModels) { + if (typeof model.commitOperations === 'function') { + model.commitOperations(this.operations); + } + } + }, + async rollback() { + this.rolledBack = true; + calls.rollbackCount += 1; + this.operations.length = 0; + this.touchedModels.clear(); + }, + }; +} + +function applyOperations(rows, operations, options = {}) { + let currentRows = Array.isArray(rows) ? rows.map(cloneRow) : []; + const keySelector = typeof options.keySelector === 'function' + ? options.keySelector + : row => row && row.id; + const assignInsertedId = Boolean(options.assignInsertedId); + + for (const operation of Array.isArray(operations) ? operations : []) { + if (operation.type === 'bulkCreate') { + const existingKeys = new Set(currentRows + .map(row => keySelector(row)) + .filter(value => value !== undefined && value !== null && value !== '')); + let nextId = currentRows.reduce((maxId, row) => { + const rowId = Number(row && row.id); + return Number.isFinite(rowId) && rowId > maxId ? rowId : maxId; + }, 0) + 1; + + for (const row of Array.isArray(operation.rows) ? operation.rows : []) { + const nextRow = cloneRow(row); + + if (assignInsertedId && (!Number.isFinite(Number(nextRow.id)) || Number(nextRow.id) <= 0)) { + nextRow.id = nextId; + nextId += 1; + } + + const rowKey = keySelector(nextRow); + + if (operation.ignoreDuplicates && rowKey !== undefined && rowKey !== null && rowKey !== '' && existingKeys.has(rowKey)) { + continue; + } + + currentRows.push(nextRow); + + if (rowKey !== undefined && rowKey !== null && rowKey !== '') { + existingKeys.add(rowKey); + } + } + + continue; + } + + if (operation.type === 'destroy') { + currentRows = currentRows.filter(row => !matchesWhere(row, operation.where)); + continue; + } + + if (operation.type === 'update') { + currentRows = currentRows.map(row => { + if (!matchesWhere(row, operation.where)) { + return row; + } + + return { + ...row, + ...(operation.values || {}), + }; + }); + } + } + + return currentRows; +} + +function createTransactionalModel(rows, capture, options = {}) { + let storedRows = Array.isArray(rows) ? rows.map(cloneRow) : []; + const modelId = options.modelId || 'model'; + const keySelector = typeof options.keySelector === 'function' + ? options.keySelector + : row => row && row.id; + const assignInsertedId = Boolean(options.assignInsertedId); + + const model = { + async findAll(query = {}) { + capture.findAllOptions.push({ + modelId, + where: query.where, + limit: query.limit, + order: query.order, + transaction: query.transaction, + }); + + const transactionOperations = query.transaction + ? query.transaction.operations.filter(operation => operation.modelId === modelId) + : []; + let visibleRows = applyOperations(storedRows, transactionOperations, { + keySelector, + assignInsertedId, + }); + + visibleRows = visibleRows.filter(row => matchesWhere(row, query.where)); + + if (Array.isArray(query.order) && query.order.length > 0) { + const [ column, direction ] = query.order[0]; + const sortFactor = String(direction || 'ASC').toUpperCase() === 'DESC' ? -1 : 1; + + visibleRows = [ ...visibleRows ].sort((left, right) => { + const leftValue = left[column]; + const rightValue = right[column]; + + if (leftValue === rightValue) { + return 0; + } + + return leftValue > rightValue ? sortFactor : -sortFactor; + }); + } + + const limitValue = query.limit === undefined ? visibleRows.length : Number.parseInt(query.limit, 10); + const limit = Number.isFinite(limitValue) ? Math.max(limitValue, 0) : visibleRows.length; + + return visibleRows.slice(0, limit).map(cloneRow); + }, + async bulkCreate(rowsToCreate, query = {}) { + capture.bulkCreateOptions.push({ + modelId, + transaction: query.transaction, + ignoreDuplicates: query.ignoreDuplicates, + }); + capture.bulkCreateRows.push({ + modelId, + rows: rowsToCreate.map(cloneRow), + }); + + const transactionOperations = query.transaction + ? query.transaction.operations.filter(operation => operation.modelId === modelId) + : []; + const visibleRows = applyOperations(storedRows, transactionOperations, { + keySelector, + assignInsertedId, + }); + const stagedRows = rowsToCreate.map(cloneRow); + + if (assignInsertedId) { + let nextId = visibleRows.reduce((maxId, row) => { + const rowId = Number(row && row.id); + return Number.isFinite(rowId) && rowId > maxId ? rowId : maxId; + }, 0) + 1; + + for (const row of stagedRows) { + if (!Number.isFinite(Number(row.id)) || Number(row.id) <= 0) { + row.id = nextId; + nextId += 1; + } + } + } + + if (query.transaction) { + query.transaction.operations.push({ + modelId, + type: 'bulkCreate', + rows: stagedRows, + ignoreDuplicates: Boolean(query.ignoreDuplicates), + }); + query.transaction.touchedModels.add(model); + } else { + storedRows = applyOperations(storedRows, [{ + modelId, + type: 'bulkCreate', + rows: stagedRows, + ignoreDuplicates: Boolean(query.ignoreDuplicates), + }], { + keySelector, + assignInsertedId, + }); + } + + return stagedRows.map(cloneRow); + }, + async destroy(query = {}) { + capture.destroyOptions.push({ + modelId, + where: query.where, + transaction: query.transaction, + }); + + if (query.transaction) { + query.transaction.operations.push({ + modelId, + type: 'destroy', + where: query.where || {}, + }); + query.transaction.touchedModels.add(model); + + return 0; + } + + const beforeCount = storedRows.length; + storedRows = storedRows.filter(row => !matchesWhere(row, query.where)); + + return beforeCount - storedRows.length; + }, + async update(values, query = {}) { + capture.updateOptions.push({ + modelId, + values: { + ...(values || {}), + }, + where: query.where, + transaction: query.transaction, + }); + capture.updateRows.push({ + modelId, + values: { + ...(values || {}), + }, + where: query.where, + }); + + const transactionOperations = query.transaction + ? query.transaction.operations.filter(operation => operation.modelId === modelId) + : []; + const visibleRows = applyOperations(storedRows, transactionOperations, { + keySelector, + assignInsertedId, + }); + const affectedCount = visibleRows.filter(row => matchesWhere(row, query.where)).length; + + if (query.transaction) { + query.transaction.operations.push({ + modelId, + type: 'update', + values: { + ...(values || {}), + }, + where: query.where || {}, + }); + query.transaction.touchedModels.add(model); + + return [ affectedCount ]; + } + + storedRows = applyOperations(storedRows, [{ + modelId, + type: 'update', + values: { + ...(values || {}), + }, + where: query.where || {}, + }], { + keySelector, + assignInsertedId, + }); + + return [ affectedCount ]; + }, + commitOperations(operations) { + const modelOperations = Array.isArray(operations) + ? operations.filter(operation => operation.modelId === modelId) + : []; + + storedRows = applyOperations(storedRows, modelOperations, { + keySelector, + assignInsertedId, + }); + }, + get rows() { + return storedRows.map(cloneRow); + }, + }; + + return model; +} + +function createHarness(options = {}) { + const capture = { + findAllOptions: [], + bulkCreateOptions: [], + bulkCreateRows: [], + destroyOptions: [], + updateOptions: [], + updateRows: [], + commitCount: 0, + rollbackCount: 0, + }; + + const sourceOrderModel = createTransactionalModel(options.sourceRows, capture, { + modelId: 'sourceOrder', + keySelector: row => row && row.id, + }); + const targetOrderModel = createTransactionalModel(options.targetRows || [], capture, { + modelId: 'targetOrder', + keySelector: row => buildDispatchKey(row), + assignInsertedId: true, + }); + const sourceItemModel = createTransactionalModel(options.sourceItemRows || [], capture, { + modelId: 'sourceItem', + keySelector: row => row && row.id, + }); + const targetItemModel = createTransactionalModel(options.targetItemRows || [], capture, { + modelId: 'targetItem', + keySelector: row => row && row.id, + }); + + const transactionCalls = []; + const ctx = { + app: { + Sequelize, + }, + logger: { + info() {}, + warn() {}, + error() {}, + debug() {}, + }, + model: { + async transaction() { + const transaction = createTransaction(capture); + transactionCalls.push(transaction); + return transaction; + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return sourceOrderModel; + }, + async getDispatchModel() { + return targetOrderModel; + }, + async listManagedTableNames() { + return [ 'wms_order_delivery_100000' ]; + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return sourceItemModel; + }, + async getDispatchModel() { + return targetItemModel; + }, + }, + }, + }; + + const service = new OrderDeliveryMigrationService(ctx); + + return { + service, + capture, + transactionCalls, + sourceOrderModel, + targetOrderModel, + sourceItemModel, + targetItemModel, + }; +} + +describe('test/app/service/systems/order_delivery_migration.test.js', () => { + it('should only migrate outbound rows that match the outbound condition', async () => { + const sourceRows = [ + { + id: 1, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'OD-00001', + step: 4, + outbound_status: 'fin', + delivery_time: new Date('2026-04-12T00:00:00Z'), + updated_at: '2026-04-12 00:00:00', + }, + { + id: 2, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'OD-00002', + step: 3, + outbound_status: 'fin', + delivery_time: new Date('2026-04-12T00:00:00Z'), + updated_at: '2026-04-12 00:00:00', + }, + { + id: 3, + warehouse_id: 100000, + store_id: 1000000, + delivery_order_code: 'OD-00003', + step: 4, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }, + ]; + const { service, capture, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1); + assert.equal(result.totalCreated, 1); + assert.equal(result.results[0].selectedCount, 1); + assert.equal(result.results[0].createdCount, 1); + assert.deepEqual(capture.findAllOptions[0].where.outbound_status[Sequelize.Op.in], [ 'fin' ]); + assert.equal(capture.findAllOptions[0].where.step, 4); + assert.equal(capture.bulkCreateRows.length, 2); + assert.equal(capture.bulkCreateRows[0].modelId, 'targetOrder'); + assert.equal(capture.bulkCreateRows[1].modelId, 'targetItem'); + assert.equal(capture.bulkCreateRows[0].rows[0].dispatch_lane, 'm4'); + assert.equal(capture.bulkCreateRows[0].rows[0].id, 1); + assert.equal(sourceOrderModel.rows.length, 2); + assert.equal(targetOrderModel.rows.length, 1); + assert.equal(sourceItemModel.rows.length, 2); + assert.equal(targetItemModel.rows.length, 1); + }); + + it('should migrate order items into dispatch table and delete source rows in the same transaction', async () => { + const sourceRows = buildOrderRows(2); + const { service, capture, transactionCalls, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 2); + assert.equal(result.totalCreated, 2); + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, true); + assert.equal(transactionCalls[0].rolledBack, false); + assert.equal(capture.findAllOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.bulkCreateOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.destroyOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(sourceOrderModel.rows.length, 0); + assert.equal(targetOrderModel.rows.length, 2); + assert.equal(sourceItemModel.rows.length, 0); + assert.equal(targetItemModel.rows.length, 2); + + assert.deepEqual(targetOrderModel.rows.map(row => row.id).sort((a, b) => a - b), [ 1, 2 ]); + const targetOrderIdSet = new Set(targetOrderModel.rows.map(row => row.id)); + assert.equal(targetItemModel.rows.every(row => targetOrderIdSet.has(Number(row.order_id))), true); + }); + + it('should cap each batch at 1000 rows and execute the insert inside one transaction', async () => { + const sourceRows = buildOrderRows(1005); + const { service, capture, transactionCalls, targetOrderModel, sourceOrderModel, targetItemModel, sourceItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1000); + assert.equal(result.totalCreated, 1000); + assert.equal(result.results[0].selectedCount, 1000); + assert.equal(capture.findAllOptions[0].limit, 1000); + assert.equal(capture.bulkCreateRows[0].rows.length, 1000); + assert.equal(capture.bulkCreateRows[1].rows.length, 1000); + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, true); + assert.equal(transactionCalls[0].rolledBack, false); + assert.equal(capture.findAllOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.bulkCreateOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(capture.destroyOptions.every(option => option.transaction === transactionCalls[0]), true); + assert.equal(targetOrderModel.rows.length, 1000); + assert.equal(targetItemModel.rows.length, 1000); + assert.equal(sourceOrderModel.rows.length, 5); + assert.equal(sourceItemModel.rows.length, 5); + }); + + it('should skip already migrated orders on repeated runs', async () => { + const sourceRows = buildOrderRows(2); + const { service, targetOrderModel, targetItemModel, sourceOrderModel, sourceItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const firstResult = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + const secondResult = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(firstResult.totalCreated, 2); + assert.equal(secondResult.totalCreated, 0); + assert.equal(targetOrderModel.rows.length, 2); + assert.equal(targetItemModel.rows.length, 2); + assert.equal(sourceOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 0); + assert.equal(new Set(targetOrderModel.rows.map(row => row.delivery_order_code)).size, 2); + assert.deepEqual(targetOrderModel.rows.map(row => row.id).sort((a, b) => a - b), [ 1, 2 ]); + }); + + it('should rollback the whole batch when any selected source row lacks dispatch key fields', async () => { + const sourceRows = buildOrderRows(2); + delete sourceRows[1].store_id; + + const { service, capture, transactionCalls, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + await assert.rejects( + service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }), + /缺少 delivery_order_code\/store_id\/warehouse_id/ + ); + + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, false); + assert.equal(transactionCalls[0].rolledBack, true); + assert.equal(capture.bulkCreateRows.length, 0); + assert.equal(capture.destroyOptions.length, 0); + assert.equal(sourceOrderModel.rows.length, 2); + assert.equal(targetOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 2); + assert.equal(targetItemModel.rows.length, 0); + }); + + it('should rollback source and target changes when item migration fails', async () => { + const sourceRows = buildOrderRows(1); + const { service, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel, transactionCalls } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + targetItemModel.bulkCreate = async () => { + throw new Error('item migration failed'); + }; + + await assert.rejects( + service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }), + /item migration failed/ + ); + + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, false); + assert.equal(transactionCalls[0].rolledBack, true); + assert.equal(sourceOrderModel.rows.length, 1); + assert.equal(targetOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 1); + assert.equal(targetItemModel.rows.length, 0); + }); + + it('should mark source orders as timeout when normal migration hits retryable lock errors', async () => { + const sourceRows = buildOrderRows(1); + const { service, capture, transactionCalls, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + targetOrderModel.bulkCreate = async () => { + throw buildRetryableDatabaseError('Lock wait timeout exceeded; try restarting transaction', 1205); + }; + + const result = await service.syncOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1); + assert.equal(result.totalCreated, 0); + assert.equal(result.totalTimeout, 1); + assert.equal(result.results[0].retryableFailure, true); + assert.equal(result.results[0].retryableFailureType, 'lock_wait_timeout'); + assert.equal(result.results[0].timeoutCount, 1); + assert.equal(transactionCalls.length, 1); + assert.equal(transactionCalls[0].committed, false); + assert.equal(transactionCalls[0].rolledBack, true); + assert.equal(capture.updateOptions.length, 1); + assert.equal(capture.updateOptions[0].values.outbound_status, 'timeout'); + assert.equal(sourceOrderModel.rows.length, 1); + assert.equal(sourceOrderModel.rows[0].outbound_status, 'timeout'); + assert.equal(targetOrderModel.rows.length, 0); + assert.equal(sourceItemModel.rows.length, 1); + assert.equal(targetItemModel.rows.length, 0); + }); + + it('should retry only timeout outbound rows in the long task', async () => { + const sourceRows = buildOrderRows(2); + sourceRows[0].outbound_status = 'timeout'; + sourceRows[1].outbound_status = 'fin'; + const { service, capture, sourceOrderModel, targetOrderModel, sourceItemModel, targetItemModel } = createHarness({ + sourceRows, + sourceItemRows: buildItemRows(sourceRows), + }); + + const result = await service.retryTimeoutOutboundOrdersToDelivery({ + warehouseIds: [ 100000 ], + }); + + assert.equal(result.totalSelected, 1); + assert.equal(result.totalCreated, 1); + assert.equal(result.totalTimeout, 0); + assert.equal(capture.findAllOptions[0].where.step, 4); + assert.deepEqual(capture.findAllOptions[0].where.outbound_status[Sequelize.Op.in], [ 'timeout' ]); + assert.equal(sourceOrderModel.rows.length, 1); + assert.equal(sourceOrderModel.rows[0].outbound_status, 'fin'); + assert.equal(targetOrderModel.rows.length, 1); + assert.equal(targetOrderModel.rows[0].id, 1); + assert.equal(sourceItemModel.rows.length, 1); + assert.equal(targetItemModel.rows.length, 1); + assert.equal(targetItemModel.rows[0].order_id, targetOrderModel.rows[0].id); + }); +}); diff --git a/test/app/service/systems/order_outbound.test.js b/test/app/service/systems/order_outbound.test.js new file mode 100644 index 0000000..df1f6d2 --- /dev/null +++ b/test/app/service/systems/order_outbound.test.js @@ -0,0 +1,166 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderOutboundService = require('../../../../app/service/systems/order_outbound'); +const { buildRows, createServiceContext, matchesWhere } = require('../../../support/order_service_test_helper'); + +/** + * 创建可回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + const storedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + capture.rows = storedRows; + + return { + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = storedRows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return storedRows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + }; +} + +/** + * 创建出库服务测试实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ service: OrderOutboundService, capture: Object }} 服务与调用记录。 + */ +function createOutboundService(rows) { + const ctx = createServiceContext(100000); + ctx.logger = { + info() {}, + warn() {}, + error() {}, + debug() {}, + }; + ctx.service = { + systems: {}, + }; + + const capture = {}; + const sharedModel = createMutableOrderModel(rows, capture); + + const service = new OrderOutboundService(ctx); + service.getOrderModel = async () => sharedModel; + + return { + service, + capture, + }; +} + +describe('test/app/service/systems/order_outbound.test.js', () => { + it('should mark single order as outbound with legacy id/order_id fields', async () => { + const scenarios = [ + { + payload: { + id: 1, + }, + expectedId: 1, + }, + { + payload: { + order_id: 2, + }, + expectedId: 2, + }, + ]; + + for (const scenario of scenarios) { + const { service, capture } = createOutboundService(buildRows(2, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markOutboundOrder(scenario.payload); + + assert.equal(capture.updateWhere.id, scenario.expectedId); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateValues.outbound_status, 'fin'); + assert.equal(capture.updateValues.step, 4); + assert.ok(capture.updateValues.delivery_time instanceof Date); + assert.ok(capture.updateValues.updated_at instanceof Date); + assert.equal(result.id, scenario.expectedId); + assert.equal(result.outbound_status, 'fin'); + assert.equal(result.step, 4); + assert.equal(result.updated_count, 1); + assert.deepEqual(result.ids, [ scenario.expectedId ]); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).outbound_status, 'fin'); + assert.equal(capture.rows.find(row => row.id === scenario.expectedId).step, 4); + } + }); + + it('should support batch ids and update delivery_time for every matched order', async () => { + const { service, capture } = createOutboundService(buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }))); + + const result = await service.markOutboundOrder({ + ids: [ 1, 3 ], + }); + + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(capture.updateValues.outbound_status, 'fin'); + assert.equal(capture.updateValues.step, 4); + assert.ok(capture.updateValues.delivery_time instanceof Date); + assert.equal(result.id, 1); + assert.equal(result.outbound_status, 'fin'); + assert.equal(result.step, 4); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + assert.equal(capture.rows.find(row => row.id === 1).outbound_status, 'fin'); + assert.equal(capture.rows.find(row => row.id === 3).outbound_status, 'fin'); + }); + + it('should reject when order ids are missing or invalid', async () => { + const { service } = createOutboundService(buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 1, + outbound_status: 'none', + delivery_time: null, + updated_at: '2026-04-12 00:00:00', + }))); + + await assert.rejects( + async () => await service.markOutboundOrder({}), + /订单ID不能为空/ + ); + + await assert.rejects( + async () => await service.markOutboundOrder({ + ids: [ 0, 'abc' ], + }), + /订单ID不能为空/ + ); + }); +}); diff --git a/test/app/service/systems/order_pending_exception.test.js b/test/app/service/systems/order_pending_exception.test.js new file mode 100644 index 0000000..c5a5286 --- /dev/null +++ b/test/app/service/systems/order_pending_exception.test.js @@ -0,0 +1,188 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderPendingExceptionService = require('../../../../app/service/systems/order_pending_exception'); +const PendingOrderService = require('../../../../app/service/systemMethods/order/pendingOrder'); +const ExpectionOrderService = require('../../../../app/service/systemMethods/order/expectionOrder'); +const { buildRows, createServiceContext, matchesWhere } = require('../../../support/order_service_test_helper'); + +/** + * 创建可回写的订单模型。 + * @param {Array} rows 初始订单数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createMutableOrderModel(rows, capture = {}) { + return { + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = rows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findAll(options = {}) { + capture.findAllWhere = options.where; + return rows + .filter(row => matchesWhere(row, options.where)) + .map(row => ({ ...row })); + }, + async count({ where } = {}) { + capture.countWhere = where; + return rows.filter(row => matchesWhere(row, where)).length; + }, + async findOne(options = {}) { + capture.findOneWhere = options.where; + const matchedRow = rows.find(row => matchesWhere(row, options.where)); + return matchedRow ? { ...matchedRow } : null; + }, + }; +} + +/** + * 创建待处理异常标记测试所需的服务实例。 + * @param {Array} rows 初始订单数据。 + * @return {{ ctx: Object, capture: Object, exceptionService: OrderPendingExceptionService, pendingService: PendingOrderService, exceptionListService: ExpectionOrderService }} 服务与调用记录。 + */ +function createServices(rows) { + const ctx = createServiceContext(100000); + ctx.logger = { + info() {}, + warn() {}, + error() {}, + debug() {}, + }; + ctx.service = { + systems: {}, + }; + + const capture = {}; + const sharedModel = createMutableOrderModel(rows, capture); + + const exceptionService = new OrderPendingExceptionService(ctx); + const pendingService = new PendingOrderService(ctx); + const exceptionListService = new ExpectionOrderService(ctx); + + exceptionService.getOrderModel = async () => sharedModel; + pendingService.getOrderModel = async () => sharedModel; + exceptionListService.getOrderModel = async () => sharedModel; + + return { + ctx, + capture, + exceptionService, + pendingService, + exceptionListService, + }; +} + +describe('test/app/service/systems/order_pending_exception.test.js', () => { + it('should mark a single order as pending exception and change list visibility', async () => { + const rows = buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '', + updated_at: '2026-04-12 00:00:00', + })); + const { capture, exceptionService, pendingService, exceptionListService } = createServices(rows); + + const pendingBefore = await pendingService.list({ where: {} }); + const exceptionBefore = await exceptionListService.list({ where: {} }); + + assert.equal(pendingBefore.list.length, 1); + assert.equal(exceptionBefore.list.length, 0); + + const result = await exceptionService.markPendingException({ + order_id: 1, + reason: '缺少异常处理单据', + }); + + assert.equal(capture.updateWhere.id, 1); + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateValues.inspection_status, 'error'); + assert.equal(capture.updateValues.step, 3); + assert.equal(capture.updateValues.order_flag, '缺少异常处理单据'); + assert.equal(result.id, 1); + assert.equal(result.inspection_status, 'error'); + assert.equal(result.step, 3); + assert.equal(result.exception_text, '缺少异常处理单据'); + assert.equal(result.order_flag, '缺少异常处理单据'); + + const pendingAfter = await pendingService.list({ where: {} }); + const exceptionAfter = await exceptionListService.list({ where: {} }); + + assert.equal(pendingAfter.list.length, 0); + assert.equal(exceptionAfter.list.length, 1); + assert.equal(exceptionAfter.list[0].step, 3); + assert.equal(exceptionAfter.list[0].inspection_status, 'error'); + assert.equal(exceptionAfter.list[0].order_flag, '缺少异常处理单据'); + }); + + it('should support batch ids and return affected ids', async () => { + const rows = buildRows(3, index => ({ + id: index + 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '', + updated_at: '2026-04-12 00:00:00', + })); + const { capture, exceptionService, pendingService, exceptionListService } = createServices(rows); + + const result = await exceptionService.markPendingException({ + ids: [ 1, 3 ], + exception_text: '批量异常标记', + }); + + assert.equal(capture.updateWhere.warehouse_id, 100000); + assert.equal(capture.updateWhere.id[Sequelize.Op.in].length, 2); + assert.ok(matchesWhere({ id: 1, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(!matchesWhere({ id: 2, warehouse_id: 100000 }, capture.updateWhere)); + assert.ok(matchesWhere({ id: 3, warehouse_id: 100000 }, capture.updateWhere)); + assert.equal(capture.updateValues.inspection_status, 'error'); + assert.equal(capture.updateValues.step, 3); + assert.equal(capture.updateValues.order_flag, '批量异常标记'); + assert.equal(result.updated_count, 2); + assert.deepEqual(result.ids, [ 1, 3 ]); + + const pendingAfter = await pendingService.list({ where: {} }); + const exceptionAfter = await exceptionListService.list({ where: {} }); + + assert.equal(pendingAfter.list.length, 1); + assert.equal(exceptionAfter.list.length, 2); + assert.ok(exceptionAfter.list.every(item => item.step === 3)); + }); + + it('should reject invalid parameters', async () => { + const rows = buildRows(1, () => ({ + id: 1, + warehouse_id: 100000, + step: 1, + inspection_status: 'fin', + order_flag: '', + updated_at: '2026-04-12 00:00:00', + })); + const { exceptionService } = createServices(rows); + + await assert.rejects( + async () => await exceptionService.markPendingException({ + id: 1, + }), + /异常文本不能为空/ + ); + + await assert.rejects( + async () => await exceptionService.markPendingException({ + exception_text: '缺少订单ID', + }), + /订单ID不能为空/ + ); + }); +}); diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js new file mode 100644 index 0000000..413874f --- /dev/null +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -0,0 +1,521 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const OrderStorageAllocationService = require('../../../../app/service/systems/order_storage_allocation'); + +/** + * 将 where 条件与测试行做最小匹配。 + * + * @param {Object} row 测试行。 + * @param {Object} where 查询条件。 + * @return {boolean} 是否匹配。 + */ +function matchesWhere(row, where) { + if (!where || typeof where !== 'object') { + return true; + } + + const andConditions = where[Sequelize.Op.and]; + if (Array.isArray(andConditions)) { + return andConditions.every(condition => matchesWhere(row, condition)); + } + + const orConditions = where[Sequelize.Op.or]; + if (Array.isArray(orConditions)) { + return orConditions.some(condition => matchesWhere(row, condition)); + } + + return Object.entries(where).every(([ fieldName, condition ]) => { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.in)) { + return Array.isArray(condition[Sequelize.Op.in]) && condition[Sequelize.Op.in].includes(row[fieldName]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) { + return row[fieldName] !== condition[Sequelize.Op.ne]; + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.gt)) { + return Number(row[fieldName]) > Number(condition[Sequelize.Op.gt]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.gte)) { + return Number(row[fieldName]) >= Number(condition[Sequelize.Op.gte]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.lt)) { + return Number(row[fieldName]) < Number(condition[Sequelize.Op.lt]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.lte)) { + return Number(row[fieldName]) <= Number(condition[Sequelize.Op.lte]); + } + } + + return row[fieldName] === condition; + }); +} + +/** + * 创建可回写的测试模型。 + * + * @param {Array} rows 行数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createMutableModel(rows, capture = {}) { + return { + async findAll(options = {}) { + capture.findAllWhere = options.where; + return rows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); + }, + async update(values = {}, options = {}) { + capture.updateValues = { ...values }; + capture.updateWhere = options.where; + + const matchedRows = rows.filter(row => matchesWhere(row, options.where)); + for (const row of matchedRows) { + Object.assign(row, values); + } + + return [ matchedRows.length ]; + }, + async findByPk(id) { + capture.findByPkId = id; + const matchedRow = rows.find(row => Number(row.id) === Number(id)); + + if (!matchedRow) { + return null; + } + + return { + ...matchedRow, + async increment(field, options = {}) { + matchedRow[field] = Number(matchedRow[field] || 0) + Number(options.by || 0); + }, + async reload() { + return this; + }, + }; + }, + }; +} + +/** + * 创建储位分配服务测试环境。 + * + * @param {Object} options 测试配置。 + * @return {{ service: OrderStorageAllocationService, captures: Object }} 测试上下文。 + */ +function createHarness(options = {}) { + const captures = { + storageLocks: [], + pickingRows: null, + }; + + const orders = Array.isArray(options.orders) ? options.orders.map(item => ({ ...item })) : []; + const orderItems = Array.isArray(options.orderItems) ? options.orderItems.map(item => ({ ...item })) : []; + const stockRows = Array.isArray(options.stockRows) ? options.stockRows.map(item => ({ ...item })) : []; + const storageRows = Array.isArray(options.storageRows) ? options.storageRows.map(item => ({ ...item })) : []; + + const ctx = { + user: { + store_id: options.warehouseId || 100000, + id: 1, + }, + logger: { + debug() {}, + info() {}, + warn() {}, + error() {}, + }, + app: { + Sequelize, + }, + model: { + async transaction() { + return { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + captures.committed = true; + }, + async rollback() { + captures.rolledBack = true; + }, + }; + }, + OrderDeliveryFactory: { + async getCurrentModel() { + return createMutableModel(orders, captures.order); + }, + }, + OrderItemsFactory: { + async getCurrentModel() { + return createMutableModel(orderItems, captures.orderItems); + }, + }, + StockWarehouse: { + async findAll(options = {}) { + captures.stockFindAllWhere = options.where; + return stockRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); + }, + async findByPk(id) { + captures.stockFindByPk = id; + const matchedRow = stockRows.find(row => Number(row.id) === Number(id)); + if (!matchedRow) { + return null; + } + + return { + ...matchedRow, + async increment(field, options = {}) { + matchedRow[field] = Number(matchedRow[field] || 0) + Number(options.by || 0); + }, + async reload() { + return this; + }, + }; + }, + }, + Storage: { + async findAll(options = {}) { + captures.storageFindAllWhere = options.where; + return storageRows.filter(row => matchesWhere(row, options.where)).map(row => ({ ...row })); + }, + }, + LocationSpace: {}, + LocationType: {}, + Picking: { + async bulkCreate(rows) { + captures.pickingRows = rows.map(row => ({ ...row })); + return rows; + }, + }, + }, + service: { + systems: { + storage: { + async lockQuantity(storageId, quantity) { + const matchedRow = storageRows.find(row => Number(row.id) === Number(storageId)); + if (!matchedRow) { + throw new Error(`库存记录不存在: ${storageId}`); + } + + const availableQuantity = Number(matchedRow.available_quantity || 0); + if (availableQuantity < Number(quantity || 0)) { + throw new Error('可用数量不足'); + } + + captures.storageLocks.push({ storageId: Number(storageId), quantity: Number(quantity) }); + matchedRow.available_quantity = availableQuantity - Number(quantity); + matchedRow.locked_quantity = Number(matchedRow.locked_quantity || 0) + Number(quantity); + return matchedRow; + }, + }, + stockStore: { + async getStoreWarehousePolicyConfigByStockId(stockId) { + return options.policies && options.policies[stockId] + ? options.policies[stockId] + : { + policyConfig: { + storage_separation: 1, + }, + allowOversell: false, + }; + }, + }, + }, + }, + }; + + const service = new OrderStorageAllocationService(ctx); + + return { + service, + captures, + ctx, + orders, + orderItems, + stockRows, + storageRows, + }; +} + +describe('test/app/service/systems/order_storage_allocation.test.js', () => { + it('should filter already allocated orders and prefer storage locations when allowed', async () => { + const { service, captures, orders, stockRows, storageRows } = createHarness({ + orders: [ + { id: 1, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 }, + { id: 2, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 11, order_id: 2, stock_id: 101, plan_qty: 2, order_line_no: '1' }, + ], + stockRows: [ + { id: 101, item_code: 'SKU-101', item_name: '测试商品101', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 1001, + warehouse_id: 100000, + stock_id: 101, + is_enabled: 1, + delete_at: null, + available_quantity: 2, + quantity: 2, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 08:00:00', + space_id: 501, + space: { + id: 501, + space_code: 'ST-001', + custom_name: '存储位A', + is_preferred_pick: false, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + { + id: 1002, + warehouse_id: 100000, + stock_id: 101, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 09:00:00', + space_id: 502, + space: { + id: 502, + space_code: 'PK-001', + custom_name: '分拣位A', + is_preferred_pick: true, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + policies: { + 101: { + policyConfig: { + storage_separation: 1, + }, + allowOversell: false, + }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 1, 2 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.allocated_order_ids.length, 1); + assert.deepEqual(result.data.skipped_orders.map(item => item.order_id), [ 1 ]); + assert.equal(result.data.orders.find(item => item.order_id === 2).storage_status, 'fin'); + assert.equal(captures.storageLocks.length, 1); + assert.equal(captures.storageLocks[0].storageId, 1001); + assert.equal(captures.pickingRows.length, 1); + assert.equal(captures.pickingRows[0].order_id, 2); + assert.equal(captures.pickingRows[0].order_item_id, 11); + assert.equal(captures.pickingRows[0].storage_id, 1001); + assert.equal(captures.pickingRows[0].quantity, 2); + assert.equal(captures.pickingRows[0].space_id, 501); + assert.equal(captures.pickingRows[0].space_name, '存储位A'); + assert.equal(captures.pickingRows[0].status, 'pending'); + assert.equal(stockRows[0].locked_quantity, 2); + assert.equal(storageRows[0].locked_quantity, 2); + assert.equal(storageRows[0].available_quantity, 0); + assert.equal(orders[1].storage_status, 'fin'); + }); + + it('should allow storage locations when storage separation is disabled even if the request flag is false', async () => { + const { service, captures, storageRows } = createHarness({ + orders: [ + { id: 3, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 31, order_id: 3, stock_id: 201, plan_qty: 1, order_line_no: '1' }, + ], + stockRows: [ + { id: 201, item_code: 'SKU-201', item_name: '测试商品201', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 2001, + warehouse_id: 100000, + stock_id: 201, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: '2026-04-10 00:00:00', + inbound_time: '2026-04-15 07:00:00', + space_id: 601, + space: { + id: 601, + space_code: 'ST-201', + custom_name: '存储位B', + is_preferred_pick: false, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + { + id: 2002, + warehouse_id: 100000, + stock_id: 201, + is_enabled: 1, + delete_at: null, + available_quantity: 1, + quantity: 1, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-14 07:00:00', + space_id: 602, + space: { + id: 602, + space_code: 'PK-201', + custom_name: '分拣位B', + is_preferred_pick: true, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + policies: { + 201: { + policyConfig: { + storage_separation: 0, + }, + allowOversell: false, + }, + }, + }); + + const result = await service.allocateStorage({ + allowStorageLocation: false, + orderIds: [ 3 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.orders[0].storage_status, 'fin'); + assert.equal(captures.storageLocks[0].storageId, 2001); + assert.equal(captures.pickingRows[0].order_id, 3); + assert.equal(captures.pickingRows[0].order_item_id, 31); + assert.equal(captures.pickingRows[0].storage_id, 2001); + assert.equal(captures.pickingRows[0].space_name, '存储位B'); + assert.equal(storageRows[0].locked_quantity, 1); + }); + + it('should allocate partially and mark shortage orders with exception text', async () => { + const { service, captures, orders, stockRows } = createHarness({ + orders: [ + { id: 4, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 41, order_id: 4, stock_id: 301, plan_qty: 3, order_line_no: '1' }, + ], + stockRows: [ + { id: 301, item_code: 'SKU-301', item_name: '测试商品301', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + { + id: 3001, + warehouse_id: 100000, + stock_id: 301, + is_enabled: 1, + delete_at: null, + available_quantity: 2, + quantity: 2, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-04-15 10:00:00', + space_id: 701, + space: { + id: 701, + space_code: 'PK-301', + custom_name: '分拣位C', + is_preferred_pick: true, + locationType: { + id: 1, + allow_allocation: 1, + is_active: 1, + }, + }, + }, + ], + policies: { + 301: { + policyConfig: { + storage_separation: 1, + }, + allowOversell: false, + }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 4 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.data.shortage_order_ids.length, 1); + assert.equal(result.data.orders.find(item => item.order_id === 4).storage_status, 'error'); + assert.equal(result.data.orders.find(item => item.order_id === 4).status, 'error'); + assert.match(result.data.shortage_messages[0], /库存不足:sku\(301\),数量:3,库位数量:2/); + assert.equal(captures.pickingRows.length, 1); + assert.equal(captures.pickingRows[0].order_id, 4); + assert.equal(captures.pickingRows[0].order_item_id, 41); + assert.equal(captures.pickingRows[0].storage_id, 3001); + assert.equal(captures.pickingRows[0].quantity, 2); + assert.equal(captures.pickingRows[0].space_name, '分拣位C'); + assert.equal(stockRows[0].locked_quantity, 2); + assert.equal(orders[0].storage_status, 'error'); + assert.equal(orders[0].order_flag, '库存不足:sku(301),数量:3,库位数量:2'); + assert.equal(captures.committed, true); + }); + + it('should return a useful summary when every order has already been allocated', async () => { + const { service, captures } = createHarness({ + orders: [ + { id: 5, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 }, + ], + orderItems: [], + stockRows: [], + storageRows: [], + }); + + const result = await service.allocateStorage({ + order_ids: [ 5 ], + allow_storage_location: true, + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '没有需要分配的订单'); + assert.equal(result.data.picking_count, 0); + assert.equal(result.data.skipped_orders[0].skipped_reason, 'already_allocated'); + assert.equal(captures.pickingRows, null); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/platform.test.js b/test/app/service/systems/platform.test.js new file mode 100644 index 0000000..379e1ae --- /dev/null +++ b/test/app/service/systems/platform.test.js @@ -0,0 +1,118 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PlatformService = require('../../../../app/service/systems/platform'); +const IndexMethodService = require('../../../../app/service/systemMethods/index'); + +function createPlatformServiceHarness(options = {}) { + const calls = { + findAll: 0, + getCache: 0, + setCache: 0, + }; + + const ctx = { + app: { + async getCacheAsync(cacheKey) { + calls.getCache += 1; + if (typeof options.getCacheAsync === 'function') { + return await options.getCacheAsync(cacheKey); + } + return options.cachedValue === undefined ? null : options.cachedValue; + }, + async setCacheAsync(cacheKey, value, ttl) { + calls.setCache += 1; + calls.cachePayload = { cacheKey, value, ttl }; + if (typeof options.setCacheAsync === 'function') { + return await options.setCacheAsync(cacheKey, value, ttl); + } + }, + }, + model: { + Platform: { + async findAll(query) { + calls.findAll += 1; + calls.findAllQuery = query; + return options.rows || [ + { code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API' }, + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS' }, + ]; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + ctx, + calls, + }; +} + +describe('test/app/service/systems/platform.test.js', () => { + it('should load platform list from database and cache it when cache is empty', async () => { + const { ctx, calls } = createPlatformServiceHarness(); + const service = new PlatformService(ctx); + + const result = await service.getPlatformList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.findAll, 1); + assert.equal(calls.setCache, 1); + assert.equal(calls.cachePayload.cacheKey, 'platform:list'); + assert.equal(calls.cachePayload.ttl, 600); + assert.deepEqual(result, [ + { code: 'JD', name: '京东平台', default_express_interface: 'OPEN_API', value: 'JD', label: '京东平台' }, + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' }, + ]); + }); + + it('should return cached platform list without querying database', async () => { + const cachedValue = [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' }, + ]; + const { ctx, calls } = createPlatformServiceHarness({ + cachedValue, + }); + const service = new PlatformService(ctx); + + const result = await service.getPlatformList(); + + assert.equal(calls.getCache, 1); + assert.equal(calls.findAll, 0); + assert.equal(calls.setCache, 0); + assert.deepEqual(result, cachedValue); + }); + + it('should delegate index.getPlatformList to the platform service', async () => { + const { ctx } = createPlatformServiceHarness(); + let serviceCalls = 0; + ctx.service = { + systems: { + platform: { + async getPlatformList() { + serviceCalls += 1; + return [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' }, + ]; + }, + }, + }, + }; + + const methodService = new IndexMethodService(ctx); + const result = await methodService.getPlatformList(); + + assert.equal(serviceCalls, 1); + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.code, 200); + assert.deepEqual(result.data, [ + { code: 'TB', name: '淘宝平台', default_express_interface: 'QM_WMS', value: 'TB', label: '淘宝平台' }, + ]); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/polo_api.test.js b/test/app/service/systems/polo_api.test.js new file mode 100644 index 0000000..da6b4c4 --- /dev/null +++ b/test/app/service/systems/polo_api.test.js @@ -0,0 +1,222 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const PoloApiService = require('../../../../app/service/systems/polo_api'); + +describe('test/app/service/systems/polo_api.test.js', () => { + it('should call test request with fixed options', async () => { + const expectedResult = { ok: true, source: 'request-result' }; + let receivedOptions = null; + + const service = new PoloApiService({ + app: { + config: {}, + }, + }); + service.client.request = async options => { + receivedOptions = options; + return expectedResult; + }; + + const result = await service.test(); + + assert.deepEqual(receivedOptions, { + method: 'Differ.JH.LogisticsPlatFeatures', + platid: 556, + bizcontent: {}, + }); + assert.strictEqual(result, expectedResult); + }); + + it('should build kuaishou request with structured inputs', async () => { + const expectedResult = { ok: true, source: 'kuaishou-request' }; + let receivedOptions = null; + + const service = new PoloApiService({ + app: { + config: {}, + }, + }); + + service.client.request = async options => { + receivedOptions = options; + return expectedResult; + }; + + const result = await service.kuaishou({ + express_id: 'KS-556', + wmsOrder: { + sourceId: 'TX-20260416-001', + sourceOrderCode: 'ORDER-20260416-001', + postcode: 'p03', + wareHouseId: 1000, + storeId: 2000, + items: 'SKU001,1,测试商品', + goodsCount: 2, + orderWeight: 3.5, + address: '广东省广州市天河区测试路 1 号', + name: '张三', + expAreaName: '天河区', + cityName: '广州市', + province: '广东省', + tempMobile: '13800000000', + tel: '13900000000', + }, + expressConfig: { + storeName: '快手店铺', + address: '广东省广州市白云区仓库路 2 号', + senderName: '李四', + districtName: '白云区;太和镇', + cityName: '广州市', + senderTel: '020-12345678', + provinceName: '广东省', + siteCode: 'SITE-001', + clientId: 'CLIENT-001', + }, + }); + + assert.deepEqual(receivedOptions, { + method: 'Differ.JH.Logistics.PostOrder', + platid: 556, + bizcontent: { + orders: [{ + businessplat: 'OTHERS', + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode: 'KS-556', + customercode: '', + customername: '快手店铺', + goods: [{ + cnname: '测试商品', + count: '2', + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: '3.5', + price: '0.0', + }], + logisticsproductname: 'JH_02', + logistictype: 'KS-556', + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: 'ORDER-20260416-001', + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: 'ORDER-20260416-001', + ProviderID: 1327, + providercode: 'KS-556', + receiver: { + address: '广东省广州市天河区测试路 1 号', + name: '张三', + area: '天河区', + city: '广州市', + mobile: '13800000000', + province: '广东省', + }, + sender: { + country: 'CN', + Company: '快手店铺', + address: '广东省广州市白云区仓库路 2 号', + name: '李四', + area: '白云区', + town: '太和镇', + city: '广州市', + phone: '020-12345678', + mobile: '020-12345678', + tel: '020-12345678', + province: '广东省', + }, + shipperno: 'CLIENT-001', + sitecode: 'SITE-001', + Inputsite: 'SITE-001', + transtype: '0', + }], + shoptype: 'JH_001', + }, + }); + assert.strictEqual(result, expectedResult); + }); + + it('should keep kuaishou fixed when a caller passes a different method and omit optional fields', async () => { + const expectedResult = { ok: true, source: 'kuaishou-defaults' }; + let receivedOptions = null; + + const service = new PoloApiService({ + app: { + config: {}, + }, + }); + + service.client.request = async options => { + receivedOptions = options; + return expectedResult; + }; + + const result = await service.kuaishou({ + method: 'Bad.Method.Should.Be.Ignored', + }); + + assert.deepEqual(receivedOptions, { + method: 'Differ.JH.Logistics.PostOrder', + platid: 556, + bizcontent: { + orders: [{ + businessplat: 'OTHERS', + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode: '', + customercode: '', + customername: '测试', + goods: [{ + cnname: '', + count: '0', + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: '0', + price: '0.0', + }], + logisticsproductname: 'JH_02', + logistictype: '', + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: '', + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: '', + ProviderID: '', + providercode: '', + receiver: { + address: '', + name: '', + area: '', + city: '', + mobile: '', + province: '', + }, + sender: { + country: 'CN', + Company: '', + address: '', + name: '', + area: '', + town: '', + city: '', + phone: '', + mobile: '', + tel: '', + province: '', + }, + shipperno: '', + sitecode: '', + Inputsite: '', + transtype: '0', + }], + shoptype: 'JH_001', + }, + }); + assert.strictEqual(result, expectedResult); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/qimen_query.test.js b/test/app/service/systems/qimen_query.test.js new file mode 100644 index 0000000..a26a931 --- /dev/null +++ b/test/app/service/systems/qimen_query.test.js @@ -0,0 +1,59 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const http = require('node:http'); +const QimenQueryService = require('../../../../app/service/systems/qimen_query'); + +describe('test/app/service/systems/qimen_query.test.js', () => { + it('should save qimen log with error info when http.request throws', async () => { + const originalRequest = http.request; + let savedLog = null; + + const ctx = { + qimenLogId: 'QL-20260414-abc123', + app: {}, + logger: { + info() {}, + warn() {}, + error() {}, + debug() {}, + }, + service: { + qimen: { + async saveQimenLog(logData) { + savedLog = { ...logData }; + return 123; + }, + }, + }, + }; + + const service = new QimenQueryService(ctx); + http.request = () => { + throw new Error('network down'); + }; + + try { + await assert.rejects( + async () => await service.sendRequest('http://example.com/router', '', { + body: '', + from_key: 'from-key', + to_key: 'to-key', + method: 'demo.method', + sign: 'demo-sign', + costomer_id: 'customer-1', + v: '2.0', + url: 'http://example.com/router', + }), + /network down/ + ); + } finally { + http.request = originalRequest; + } + + assert.ok(savedLog); + assert.equal(savedLog.log_id, 'QL-20260414-abc123'); + assert.equal(savedLog.body, ''); + assert.match(savedLog.result, /network down/); + }); +}); diff --git a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js index cff7740..e469840 100644 --- a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +++ b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js @@ -7,8 +7,14 @@ function createTestContext(options = {}) { const calls = { countArgs: null, findArgs: null, + findOneArgs: null, + updateArgs: null, barcodeCalls: [], fileRefArgs: null, + transactionCount: 0, + transactionCommits: 0, + transactionRollbacks: 0, + operationLogCalls: [], }; const Op = { @@ -64,6 +70,14 @@ function createTestContext(options = {}) { calls.findArgs = args; return rows; }, + async findOne(args) { + calls.findOneArgs = args; + return options.stockInfo || null; + }, + async update(args) { + calls.updateArgs = args; + return [ 1 ]; + }, }, StockBarcode: { async findAll(args) { @@ -113,6 +127,27 @@ function createTestContext(options = {}) { logger: { error() {}, }, + service: { + systems: { + operationLog: { + async createOperationLog(args) { + calls.operationLogCalls.push(args); + }, + }, + }, + }, + }; + + model.transaction = async () => { + calls.transactionCount += 1; + return { + async commit() { + calls.transactionCommits += 1; + }, + async rollback() { + calls.transactionRollbacks += 1; + }, + }; }; return { @@ -317,4 +352,251 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js assert.match(result.message, /筛选条件解析失败/); assert.match(result.message, /字段 item_code 条件必须是对象/); }); + + it('should return shelf life management flag as boolean in search result', async () => { + const { service, calls } = createServiceHarness({ + rows: [{ + toJSON() { + return { + id: 1, + item_code: 'SKU-1', + goods_code: 'G-1', + item_name: '商品A', + sku_property: '默认规格', + stock_unit: '件', + quantity: 10, + locked_quantity: 2, + brand_name: '品牌A', + item_type: 'normal', + is_batch_mgmt: 'Y', + is_shelf_life_mgmt: 'Y', + barcodes: [{ barcode: 'BC-1' }], + store_stock: { + store_id: 100000, + store_remask: '主仓', + }, + }; + }, + }], + }); + + const result = await service.search({ + keyword: '', + }); + + assert.equal(result.code, 200); + assert.equal(Array.isArray(result.data), true); + assert.equal(result.data.length, 1); + assert.equal(Object.prototype.hasOwnProperty.call(result.data[0], 'is_batch_mgmt_enabled'), true); + assert.equal(typeof result.data[0].is_batch_mgmt_enabled, 'boolean'); + assert.equal(result.data[0].is_batch_mgmt_enabled, true); + assert.equal(Object.prototype.hasOwnProperty.call(result.data[0], 'is_batch_mgmt'), false); + assert.equal(Object.prototype.hasOwnProperty.call(result.data[0], 'is_shelf_life_mgmt'), true); + assert.equal(typeof result.data[0].is_shelf_life_mgmt, 'boolean'); + assert.equal(result.data[0].is_shelf_life_mgmt, true); + assert.deepEqual(result.data[0].barcodes, [ 'BC-1' ]); + assert.ok(calls.findArgs); + assert.ok(calls.findArgs.attributes.includes('is_shelf_life_mgmt')); + }); + + it('should return shelf life threshold fields in search result', async () => { + const { service, calls } = createServiceHarness({ + rows: [{ + toJSON() { + return { + id: 2, + item_code: 'SKU-2', + goods_code: 'G-2', + item_name: '商品B', + sku_property: '默认规格', + stock_unit: '件', + quantity: 8, + locked_quantity: 1, + brand_name: '品牌B', + item_type: 'normal', + inbound_min_days: 3, + outbound_min_days: 5, + shelf_life_days: 30, + remaining_threshold_days: 7, + is_shelf_life_mgmt: 'N', + barcodes: [], + store_stock: { + store_id: 100000, + store_remask: '主仓', + }, + }; + }, + }], + }); + + const result = await service.search({ + keyword: '', + }); + + assert.equal(result.code, 200); + assert.equal(result.data.length, 1); + assert.equal(result.data[0].inbound_min_days, 3); + assert.equal(result.data[0].outbound_min_days, 5); + assert.equal(result.data[0].shelf_life_days, 30); + assert.equal(result.data[0].remaining_threshold_days, 7); + assert.equal(typeof result.data[0].inbound_min_days, 'number'); + assert.equal(typeof result.data[0].outbound_min_days, 'number'); + assert.equal(typeof result.data[0].shelf_life_days, 'number'); + assert.equal(typeof result.data[0].remaining_threshold_days, 'number'); + assert.ok(calls.findArgs); + for (const field of [ 'inbound_min_days', 'outbound_min_days', 'shelf_life_days', 'remaining_threshold_days' ]) { + assert.ok(calls.findArgs.attributes.includes(field)); + } + }); + + it('should return warehouse day threshold fields in getInfo response', async () => { + const { service, calls } = createServiceHarness({ + stockInfo: { + id: 1, + item_code: 'SKU-1', + shelf_life_days: 10, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + enable_box_spec: 1, + }, + }); + + const result = await service.getInfo({ + id: 1, + }); + + assert.equal(result.id, 1); + assert.equal(result.shelf_life_days, 10); + assert.equal(result.inbound_min_days, 3); + assert.equal(result.outbound_min_days, 5); + assert.equal(result.remaining_threshold_days, 7); + assert.equal(result.enable_box_spec, true); + assert.ok(calls.findOneArgs); + assert.ok(calls.findOneArgs.attributes.includes('shelf_life_days')); + assert.ok(calls.findOneArgs.attributes.includes('inbound_min_days')); + assert.ok(calls.findOneArgs.attributes.includes('outbound_min_days')); + assert.ok(calls.findOneArgs.attributes.includes('remaining_threshold_days')); + }); + + it('should persist shelf life fields when saving warehouse stock', async () => { + const { service, calls } = createServiceHarness({ + stockInfo: { + id: 9, + deleted_at: null, + }, + }); + + service.getInfo = async ({ id }) => ({ + id, + shelf_life_days: 30, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + }); + + const result = await service.saveWarehouseStock({ + id: 9, + item_code: 'SKU-9', + item_name: '商品九号', + sku_property: '默认规格', + stock_unit: '件', + packing_requirements: '', + length: 10, + width: 11, + height: 12, + volume: 13, + gross_weight: 14, + net_weight: 15, + tag_price: 16, + retail_price: 17, + is_sn_mgmt: 'N', + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'N', + prohibited_id: null, + brand_name: '品牌九', + managementFlags: '', + enable_box_spec: false, + box_unit: '', + quantity_per_box: 0, + box_gross_weight: 0, + box_net_weight: 0, + box_length: 0, + box_width: 0, + box_height: 0, + box_volume: 0, + box_remark: '', + shelf_life_days: 30, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + }); + + assert.equal(result.id, 9); + assert.equal(calls.transactionCount, 1); + assert.equal(calls.transactionCommits, 1); + assert.equal(calls.transactionRollbacks, 0); + assert.ok(calls.updateArgs); + assert.equal(calls.updateArgs.shelf_life_days, 30); + assert.equal(calls.updateArgs.inbound_min_days, 3); + assert.equal(calls.updateArgs.outbound_min_days, 5); + assert.equal(calls.updateArgs.remaining_threshold_days, 7); + assert.equal(calls.operationLogCalls.length, 1); + }); + + it('should reject saving warehouse stock when shelf life fields are missing or invalid', async () => { + const { service, calls } = createServiceHarness({ + stockInfo: { + id: 10, + deleted_at: null, + }, + }); + + await assert.rejects( + service.saveWarehouseStock({ + id: 10, + item_code: 'SKU-10', + item_name: '商品十号', + sku_property: '默认规格', + stock_unit: '件', + packing_requirements: '', + length: 10, + width: 11, + height: 12, + volume: 13, + gross_weight: 14, + net_weight: 15, + tag_price: 16, + retail_price: 17, + is_sn_mgmt: 'N', + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'N', + prohibited_id: null, + brand_name: '品牌十', + managementFlags: '', + enable_box_spec: false, + box_unit: '', + quantity_per_box: 0, + box_gross_weight: 0, + box_net_weight: 0, + box_length: 0, + box_width: 0, + box_height: 0, + box_volume: 0, + box_remark: '', + shelf_life_days: 0, + inbound_min_days: 3, + outbound_min_days: 5, + remaining_threshold_days: 7, + }), + error => { + assert.equal(error.message, '启用保质期管理时,shelf_life_days、inbound_min_days、outbound_min_days、remaining_threshold_days 都必须存在且大于 0'); + return true; + } + ); + + assert.equal(calls.transactionCount, 0); + assert.equal(calls.updateArgs, null); + assert.equal(calls.operationLogCalls.length, 0); + }); }); diff --git a/test/app/service/systems/storage.expiry.test.js b/test/app/service/systems/storage.expiry.test.js new file mode 100644 index 0000000..d37e580 --- /dev/null +++ b/test/app/service/systems/storage.expiry.test.js @@ -0,0 +1,227 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageExpiryService = require('../../../../app/service/systems/storage/expiry'); +const StorageExpiryMethodService = require('../../../../app/service/systemMethods/storage/expiry'); + +function createServiceHarness(options = {}) { + const calls = { + findArgs: null, + }; + + const Op = { + and: '$and', + gt: '$gt', + ne: '$ne', + }; + + const rows = options.rows || [{ + get() { + return { + id: 11, + warehouse_id: 100000, + store_id: 100001, + space_id: 9, + stock_id: 88, + batch_no: 'BATCH-1', + inventory_type: 'ZP', + quantity: 10, + locked_quantity: 1, + available_quantity: 9, + production_date: '2026-04-01 00:00:00', + expiry_date: '2026-04-10 00:00:00', + inbound_time: '2026-04-02 00:00:00', + created_at: '2026-04-02 00:00:00', + updated_at: '2026-04-03 00:00:00', + stock: { + id: 88, + item_code: 'SKU-88', + goods_code: 'G-88', + item_name: '测试商品', + sku_property: '默认规格', + stock_unit: '件', + store_id: 100001, + warehouse_id: 100000, + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: 15, + }, + space: { + id: 9, + space_code: 'A-01', + custom_name: '一号位', + }, + }; + }, + }]; + + const model = { + Storage: { + async findAndCountAll(args) { + calls.findArgs = args; + return { + count: options.total ?? rows.length, + rows, + }; + }, + }, + StockWarehouse: {}, + LocationSpace: {}, + }; + + const app = { + Sequelize: { Op, literal: value => ({ literal: value }) }, + model, + formatDate(value) { + return String(value).slice(0, 10); + }, + }; + + const ctx = { + app, + model, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + app, + ctx, + model, + calls, + Op, + }; +} + +describe('test/app/service/systems/storage.expiry.test.js', () => { + it('should query expiry list by current warehouse and shelf-life stock include', async () => { + const harness = createServiceHarness(); + const service = new StorageExpiryService(harness.ctx); + harness.ctx.whereParsed = { + dynamicConditions: [ + { inventory_type: 'ZP' }, + ], + bucketConditions: { + stock: [ + { item_code: { $like: '%SKU%' } }, + ], + }, + }; + + const result = await service.list({ + where: { + item_code: { + operator: 'like', + value: 'SKU', + }, + }, + }, { + page: 2, + pageSize: 5, + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '查询成功'); + assert.equal(result.data.pagination.page, 2); + assert.equal(result.data.pagination.pageSize, 5); + assert.equal(result.data.list.length, 1); + assert.equal(result.data.list[0].threshold_days, 15); + assert.equal(result.data.list[0].remaining_days >= 0, true); + assert.equal(result.data.list[0].stock.item_code, 'SKU-88'); + assert.ok(harness.calls.findArgs); + assert.equal(harness.calls.findArgs.include[0].as, 'stock'); + assert.equal(harness.calls.findArgs.where.$and[0].warehouse_id, 100000); + }); + + it('should return empty pagination when user has no warehouse', async () => { + const harness = createServiceHarness(); + harness.ctx.user.store_id = 0; + const service = new StorageExpiryService(harness.ctx); + + const result = await service.list(); + + assert.equal(result.code, 400); + assert.equal(result.data.list.length, 0); + assert.equal(result.data.pagination.total, 0); + }); + + it('should pass normalized where and pagination through systemMethods wrapper', async () => { + const captured = { + where: null, + pagination: null, + }; + + const Op = { + and: '$and', + gt: '$gt', + ne: '$ne', + like: '$like', + }; + + const ctx = { + app: { + Sequelize: { Op }, + }, + service: { + systems: { + storage: { + expiry: { + async list(where, pagination) { + captured.where = where; + captured.pagination = pagination; + return { + code: 200, + message: '查询成功', + data: { + list: [], + pagination: { + page: 1, + pageSize: 20, + total: 0, + totalPages: 0, + hasPrevious: false, + hasNext: false, + }, + }, + }; + }, + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + user: { + store_id: 100000, + }, + }; + + const methodService = new StorageExpiryMethodService(ctx); + const result = await methodService.list({ + where: { + item_name: { + operator: 'like', + value: '苹果', + }, + }, + pagination: { + page: 3, + pageSize: 7, + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(captured.pagination.page, 3); + assert.equal(captured.pagination.pageSize, 7); + assert.equal(captured.where.item_name.operator, 'like'); + }); +}); diff --git a/test/app/service/systems/storage.inventory.test.js b/test/app/service/systems/storage.inventory.test.js new file mode 100644 index 0000000..c047d26 --- /dev/null +++ b/test/app/service/systems/storage.inventory.test.js @@ -0,0 +1,390 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageInventoryService = require('../../../../app/service/systems/storage/inventory'); + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * 将指定偏移天数转换为用于测试的日期时间字符串。 + * + * @param {number} dayOffset 相对当前时间的天数偏移 + * @return {string} 日期时间字符串 + */ +function toDateTimeString(dayOffset) { + const value = new Date(Date.now() + (dayOffset * DAY_MS)).toISOString().replace('T', ' '); + return value.slice(0, 19); +} + +/** + * 生成带 get 方法的 Sequelize 模型行对象。 + * + * @param {Object} plain 原始对象 + * @return {Object} 模型行对象 + */ +function createModelRow(plain) { + return { + get() { + return plain; + }, + }; +} + +/** + * 创建库存列表服务测试支架。 + * + * @param {Object} [options={}] 测试选项 + * @param {Object[]} [options.batchRows=[]] 批次模式返回行 + * @param {Object[]} [options.mergedRows=[]] 合并模式返回行 + * @param {number} [options.batchTotal] 批次模式总数 + * @param {number} [options.mergedTotal] 合并模式总数 + * @return {Object} 测试支架 + */ +function createServiceHarness(options = {}) { + const batchRows = Array.isArray(options.batchRows) ? options.batchRows.map(createModelRow) : []; + const mergedRows = Array.isArray(options.mergedRows) ? options.mergedRows : []; + const calls = { + findAndCountAllArgs: null, + countArgs: null, + findAllArgs: null, + stockBarcodeArgs: [], + fileReferenceArgs: [], + }; + + const Op = { + and: '$and', + gt: '$gt', + ne: '$ne', + in: '$in', + }; + + const stockBarcodes = Array.isArray(options.stockBarcodes) ? options.stockBarcodes : []; + const fileReferences = Array.isArray(options.fileReferences) ? options.fileReferences : []; + + const model = { + Storage: { + async findAndCountAll(args) { + calls.findAndCountAllArgs = args; + return { + count: options.batchTotal ?? batchRows.length, + rows: batchRows, + }; + }, + async count(args) { + calls.countArgs = args; + return options.mergedTotal ?? mergedRows.length; + }, + async findAll(args) { + calls.findAllArgs = args; + return mergedRows; + }, + }, + StockWarehouse: {}, + StockBarcode: { + async findAll(args) { + calls.stockBarcodeArgs.push(args); + const stockIdCondition = args?.where?.stock_id || {}; + const stockIds = Array.isArray(stockIdCondition[Op.in]) ? stockIdCondition[Op.in].map(Number) : []; + return stockBarcodes.filter(item => stockIds.includes(Number(item.stock_id))); + }, + }, + FileReference: { + async findAll(args) { + calls.fileReferenceArgs.push(args); + const businessIdCondition = args?.where?.business_id || {}; + const businessIds = Array.isArray(businessIdCondition[Op.in]) ? businessIdCondition[Op.in].map(Number) : []; + return fileReferences.filter(item => businessIds.includes(Number(item.business_id))); + }, + }, + File: {}, + LocationSpace: {}, + }; + + const app = { + Sequelize: { + Op, + fn(name, field) { + return { fn: name, field }; + }, + col(value) { + return { col: value }; + }, + literal(value) { + return { literal: value }; + }, + }, + model, + formatDate(value) { + return String(value).slice(0, 10); + }, + }; + + const ctx = { + app, + model, + user: { + store_id: 100000, + }, + whereParsed: { + dynamicConditions: [], + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return { + app, + ctx, + model, + calls, + }; +} + +describe('test/app/service/systems/storage.inventory.test.js', () => { + it('should return production and expiry dates with warning flag for batch list', async () => { + const productionDate = toDateTimeString(-6); + const expiryDate = toDateTimeString(4); + const expectedProductionDate = productionDate.slice(0, 10); + const expectedExpiryDate = expiryDate.slice(0, 10); + const harness = createServiceHarness({ + batchRows: [{ + id: 1, + stock_id: 88, + space_id: 9, + inventory_type: 'ZP', + warehouse_id: 100000, + store_id: 100001, + quantity: 12, + locked_quantity: 2, + available_quantity: 10, + created_at: toDateTimeString(-10), + updated_at: toDateTimeString(-1), + inbound_time: toDateTimeString(-3), + production_date: productionDate, + expiry_date: expiryDate, + stock: { + id: 88, + item_code: 'SKU-88', + item_name: '测试商品', + sku_property: '默认规格', + stock_unit: '件', + is_batch_mgmt: 'Y', + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: 5, + store_stock: { + store_id: 100001, + store_remask: '测试货主名称', + }, + }, + space: { + id: 9, + space_code: 'A-01', + custom_name: '一号位', + }, + }], + stockBarcodes: [ + { stock_id: 88, barcode: 'BC-88-A' }, + { stock_id: 88, barcode: 'BC-88-B' }, + ], + fileReferences: [ + { + business_id: 88, + file_id: 70088, + file: { + file_url: 'https://example.com/stock-88-a.jpg', + }, + }, + { + business_id: 88, + file_id: 70089, + file: { + file_url: 'https://example.com/stock-88-b.jpg', + }, + }, + ], + }); + const service = new StorageInventoryService(harness.ctx); + + const result = await service.getInventoryList( + { page: 1, pageSize: 10 }, + { sortField: 'created_at', sortOrder: 'DESC' }, + true + ); + + assert.equal(result.list.length, 1); + assert.equal(result.pagination.page, 1); + assert.equal(result.pagination.pageSize, 10); + assert.equal(result.pagination.total, 1); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'production_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'expiry_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'is_shelf_life_warning_triggered'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt_enabled'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt'), false); + assert.equal(result.list[0].production_date, expectedProductionDate); + assert.equal(result.list[0].expiry_date, expectedExpiryDate); + assert.equal(result.list[0].is_shelf_life_warning_triggered, true); + assert.equal(result.list[0].stock.is_batch_mgmt_enabled, true); + assert.equal(result.list[0].stock.store_name, '测试货主名称'); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'store_stock'), false); + assert.deepEqual(result.list[0].stock.barcodes, [ 'BC-88-A', 'BC-88-B' ]); + assert.deepEqual(result.list[0].stock.images, [ + 'https://example.com/stock-88-a.jpg', + 'https://example.com/stock-88-b.jpg', + ]); + assert.ok(harness.calls.findAndCountAllArgs); + assert.ok(harness.calls.findAndCountAllArgs.include[0].attributes.includes('is_shelf_life_mgmt')); + assert.ok(harness.calls.findAndCountAllArgs.include[0].attributes.includes('is_batch_mgmt')); + assert.ok(harness.calls.findAndCountAllArgs.include[0].attributes.includes('remaining_threshold_days')); + assert.ok(Array.isArray(harness.calls.findAndCountAllArgs.include[0].include)); + assert.equal(harness.calls.findAndCountAllArgs.include[0].include[0].as, 'store_stock'); + assert.deepEqual(harness.calls.findAndCountAllArgs.include[0].include[0].attributes, [ 'store_id', 'store_remask' ]); + assert.equal(harness.calls.stockBarcodeArgs.length, 1); + assert.equal(harness.calls.fileReferenceArgs.length, 1); + }); + + it('should return warning flag false when shelf-life management is disabled', async () => { + const productionDate = toDateTimeString(-4); + const expiryDate = toDateTimeString(2); + const expectedProductionDate = productionDate.slice(0, 10); + const expectedExpiryDate = expiryDate.slice(0, 10); + const harness = createServiceHarness({ + batchRows: [{ + id: 2, + stock_id: 89, + space_id: 10, + inventory_type: 'ZP', + warehouse_id: 100000, + store_id: 100001, + quantity: 8, + locked_quantity: 0, + available_quantity: 8, + created_at: toDateTimeString(-8), + updated_at: toDateTimeString(-2), + inbound_time: toDateTimeString(-2), + production_date: productionDate, + expiry_date: expiryDate, + stock: { + id: 89, + item_code: 'SKU-89', + item_name: '未启用保质期管理商品', + sku_property: '默认规格', + stock_unit: '箱', + is_batch_mgmt: 'N', + is_shelf_life_mgmt: 'N', + remaining_threshold_days: 5, + }, + space: { + id: 10, + space_code: 'B-01', + custom_name: '二号位', + }, + }], + stockBarcodes: [], + fileReferences: [], + }); + const service = new StorageInventoryService(harness.ctx); + + const result = await service.getInventoryList({}, {}, true); + + assert.equal(result.list.length, 1); + assert.equal(result.list[0].is_shelf_life_warning_triggered, false); + assert.equal(result.list[0].stock.is_batch_mgmt_enabled, false); + assert.equal(result.list[0].stock.store_name, null); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt'), false); + assert.equal(result.list[0].production_date, expectedProductionDate); + assert.equal(result.list[0].expiry_date, expectedExpiryDate); + assert.deepEqual(result.list[0].stock.barcodes, []); + assert.deepEqual(result.list[0].stock.images, []); + }); + + it('should return merged list with earliest production and expiry dates', async () => { + const productionDate = toDateTimeString(-9); + const expiryDate = toDateTimeString(3); + const harness = createServiceHarness({ + mergedTotal: 1, + mergedRows: [{ + stock_id: 90, + space_id: 11, + inventory_type: 'ZP', + warehouse_id: 100000, + store_id: 100001, + quantity: 20, + locked_quantity: 3, + available_quantity: 17, + production_date: productionDate, + expiry_date: expiryDate, + first_inbound_time: toDateTimeString(-7), + last_inbound_time: toDateTimeString(-1), + batch_count: 2, + stock: { + id: 90, + item_code: 'SKU-90', + item_name: '合并库存商品', + sku_property: '默认规格', + stock_unit: '件', + is_batch_mgmt: 'Y', + is_shelf_life_mgmt: 'Y', + remaining_threshold_days: 5, + store_stock: { + store_id: 100002, + store_remask: '合并货主名称', + }, + }, + space: { + id: 11, + space_code: 'C-01', + custom_name: '三号位', + }, + }], + stockBarcodes: [ + { stock_id: 90, barcode: 'BC-90-A' }, + ], + fileReferences: [ + { + business_id: 90, + file_id: 70090, + file: { + file_url: 'https://example.com/stock-90-a.jpg', + }, + }, + ], + }); + const service = new StorageInventoryService(harness.ctx); + + const result = await service.getInventoryList( + { page: 2, pageSize: 5 }, + { sortField: 'last_inbound_time', sortOrder: 'ASC' }, + false + ); + + assert.equal(result.list.length, 1); + assert.equal(result.pagination.page, 2); + assert.equal(result.pagination.pageSize, 5); + assert.equal(result.pagination.total, 1); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'production_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'expiry_date'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0], 'is_shelf_life_warning_triggered'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt_enabled'), true); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'is_batch_mgmt'), false); + assert.equal(result.list[0].production_date, productionDate.slice(0, 10)); + assert.equal(result.list[0].expiry_date, expiryDate.slice(0, 10)); + assert.equal(result.list[0].is_shelf_life_warning_triggered, true); + assert.equal(result.list[0].stock.is_batch_mgmt_enabled, true); + assert.equal(result.list[0].stock.store_name, '合并货主名称'); + assert.equal(Object.prototype.hasOwnProperty.call(result.list[0].stock, 'store_stock'), false); + assert.deepEqual(result.list[0].stock.barcodes, [ 'BC-90-A' ]); + assert.deepEqual(result.list[0].stock.images, [ 'https://example.com/stock-90-a.jpg' ]); + assert.ok(harness.calls.findAllArgs); + assert.ok(harness.calls.findAllArgs.attributes.some(item => Array.isArray(item) && item[1] === 'production_date' && item[0].fn === 'MIN')); + assert.ok(harness.calls.findAllArgs.attributes.some(item => Array.isArray(item) && item[1] === 'expiry_date' && item[0].fn === 'MIN')); + assert.ok(harness.calls.findAllArgs.include[0].attributes.includes('is_batch_mgmt')); + assert.ok(Array.isArray(harness.calls.findAllArgs.include[0].include)); + assert.equal(harness.calls.findAllArgs.include[0].include[0].as, 'store_stock'); + assert.deepEqual(harness.calls.findAllArgs.include[0].include[0].attributes, [ 'store_id', 'store_remask' ]); + assert.equal(harness.calls.stockBarcodeArgs.length, 1); + assert.equal(harness.calls.fileReferenceArgs.length, 1); + }); +}); diff --git a/test/app/service/systems/storage.receiving.detailChange.test.js b/test/app/service/systems/storage.receiving.detailChange.test.js new file mode 100644 index 0000000..4a37977 --- /dev/null +++ b/test/app/service/systems/storage.receiving.detailChange.test.js @@ -0,0 +1,127 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ReceivingService = require('../../../../app/service/systems/storage/receiving'); + +function formatDate(date, formatStr = 'YYYY-MM-DD HH:mm:ss') { + const targetDate = date instanceof Date ? date : new Date(date); + const year = targetDate.getFullYear(); + const month = String(targetDate.getMonth() + 1).padStart(2, '0'); + const day = String(targetDate.getDate()).padStart(2, '0'); + const hours = String(targetDate.getHours()).padStart(2, '0'); + const minutes = String(targetDate.getMinutes()).padStart(2, '0'); + const seconds = String(targetDate.getSeconds()).padStart(2, '0'); + + return formatStr + .replace('YYYY', year) + .replace('MM', month) + .replace('DD', day) + .replace('HH', hours) + .replace('mm', minutes) + .replace('ss', seconds); +} + +function createServiceHarness() { + const calls = { + detailUpdate: 0, + }; + + const model = { + ReceivingDetail: { + async findOne() { + return { + id: 501, + receiving_id: 123, + product_name: '测试商品', + actual_quantity: 1, + barcode: '', + system_product_id: null, + updated_at: new Date('2026-04-01T00:00:00Z'), + }; + }, + async update() { + calls.detailUpdate += 1; + }, + }, + Receiving: { + async findOne() { + return { + id: 123, + warehouse_id: 100000, + store_id: 1000000, + store_name: '测试货主', + status: 'receiving', + }; + }, + }, + StockWarehouse: { + async findOne() { + throw new Error('should not be called'); + }, + }, + LocationSpace: { + async findOne() { + throw new Error('should not be called'); + }, + }, + StoreWarehouse: { + buildStoreStockInclude() { + return {}; + }, + }, + }; + + const ctx = { + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + operationLog: { + async createOperationLog() { + calls.operationLog = (calls.operationLog || 0) + 1; + }, + }, + }, + }, + model, + app: { + model, + Sequelize: { + Op: { + or: 'or', + }, + }, + formatDate, + }, + }; + + const service = new ReceivingService(ctx); + return { + service, + calls, + }; +} + +describe('test/app/service/systems/storage.receiving.detailChange.test.js', () => { + it('should reject expired expiry_date before updating receiving detail', async () => { + const { service, calls } = createServiceHarness(); + + const result = await service.detailChange({ + id: 501, + receiving_id: 123, + actual_quantity: 1, + expiry_date: '2000-01-01', + }); + + assert.equal(result.code, 400); + assert.equal(result.message, '到期日期已过期,不能录入收货'); + assert.equal(calls.detailUpdate, 0); + assert.equal(calls.operationLog || 0, 0); + }); +}); diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js index 5775d92..a469705 100644 --- a/test/app/service/systems/storage.receiving.report.test.js +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -2,6 +2,11 @@ const assert = require('node:assert/strict'); const ReceivingService = require('../../../../app/service/systems/storage/receiving'); +const DAY_MS = 24 * 60 * 60 * 1000; + +function daysFromNow(days) { + return new Date(Date.now() + (days * DAY_MS)); +} function createService() { const excelCalls = []; @@ -65,6 +70,8 @@ function createService() { function createCompleteReceivingService({ uploadShouldFail = false, detailOverrides = {}, + systemProductOverrides = {}, + hydrateSystemProductFromQuery = false, itemImages, } = {}) { const steps = []; @@ -91,6 +98,19 @@ function createCompleteReceivingService({ barcode: 'SKU-001', actual_quantity: 8, weight: 12, + production_date: null, + expiry_date: null, + system_product: { + id: 10001, + item_name: '测试商品A', + item_code: 'SKU-001', + inbound_min_days: 0, + shelf_life_days: 0, + remaining_threshold_days: 0, + is_shelf_life_mgmt: 'N', + is_batch_mgmt: 'N', + ...systemProductOverrides, + }, ...detailOverrides, }; @@ -127,7 +147,29 @@ function createCompleteReceivingService({ return transaction; }, Receiving: { - async findOne() { + async findOne(options = {}) { + const includeSystemProduct = hydrateSystemProductFromQuery + && Array.isArray(options.include) + && options.include.some(includeItem => Array.isArray(includeItem && includeItem.include) + && includeItem.include.some(childInclude => childInclude && childInclude.as === 'system_product')); + + const receivingDetail = includeSystemProduct && !detailRecord.system_product + ? { + ...detailRecord, + system_product: { + id: 10001, + item_name: '测试商品A', + item_code: 'SKU-001', + inbound_min_days: 0, + shelf_life_days: 0, + remaining_threshold_days: 0, + is_shelf_life_mgmt: 'N', + is_batch_mgmt: 'N', + ...systemProductOverrides, + }, + } + : detailRecord; + return { id: 123, warehouse_id: 100000, @@ -136,7 +178,7 @@ function createCompleteReceivingService({ receiving_number: 'RCV202604040001', status: 'receiving', remark: '', - details: [ detailRecord ], + details: [ receivingDetail ], }; }, async update() { @@ -168,8 +210,8 @@ function createCompleteReceivingService({ throw new Error('upload failed'); } return { - fileKey: '收货完成_RCV202604040001.xlsx', - url: 'https://cdn.example.com/收货完成_RCV202604040001.xlsx', + fileKey: '收货明细(已完成收货)_RCV202604040001.xlsx', + url: 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx', }; }; @@ -257,7 +299,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(excelCalls.length, 1); const [ options ] = excelCalls; - assert.equal(options.filename, '收货完成_RCV202604040001.xlsx'); + assert.equal(options.filename, '收货明细(已完成收货)_RCV202604040001.xlsx'); assert.ok(String(options.dir || '').includes('receiving/completed')); assert.equal(options.expireDays, 90); assert.ok(Array.isArray(options.sheets)); @@ -291,7 +333,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.ok(sheet.styledRows.some(item => item && item.style && item.style.font && item.style.font.bold), '应包含表头加粗样式'); assert.ok(Array.isArray(sheet.embeddedImages)); assert.equal(sheet.embeddedImages.length, 3); - assert.equal(result.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + assert.equal(result.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx'); }); it('should send receiving completed notice with the unified event payload', async () => { @@ -315,8 +357,8 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { total_quantity: 8, }, completionReport: { - fileKey: '收货完成_RCV202604040001.xlsx', - url: 'https://cdn.example.com/收货完成_RCV202604040001.xlsx', + fileKey: '收货明细(已完成收货)_RCV202604040001.xlsx', + url: 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx', }, }); @@ -327,7 +369,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(options.businessName, 'receiving'); assert.equal(options.event, 'receiving_completed'); assert.equal(options.messageType, 'file'); - assert.equal(options.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + assert.equal(options.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx'); assert.equal(options.subject.id, 100000); assert.equal(options.subject.name, '测试仓库'); assert.match(String(options.content || ''), /收货单号:RCV202604040001 已完成/); @@ -539,7 +581,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(noticeCalls.length, 2); assert.equal(noticeCalls[0].completionReport ?? null, null); assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000); - assert.equal(noticeCalls[1].completionReport.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + assert.equal(noticeCalls[1].completionReport.url, 'https://cdn.example.com/收货明细(已完成收货)_RCV202604040001.xlsx'); }); it('should only send text notice when completion excel generation fails', async () => { @@ -557,15 +599,122 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(Number(noticeCalls[0].receiving.store_id), 1000000); }); - it('should still complete and notify when detail has no matched product or completeness fields', async () => { + it('should reject completion when batch-managed product misses batch number', async () => { const { service, steps, noticeCalls } = createCompleteReceivingService({ detailOverrides: { - system_product_id: null, - barcode: '', - weight: 0, - actual_quantity: 1, + system_product: null, + batch_number: ' ', + production_date: daysFromNow(-10), + expiry_date: daysFromNow(30), + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, + }, + hydrateSystemProductFromQuery: true, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'BATCH_NUMBER_REQUIRED'); + assert.match(result.message, /批次号/); + assert.ok(Array.isArray(result.data.invalid_details)); + assert.equal(result.data.invalid_details[0].detail_id, 501); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should reject completion when batch-managed product misses production date or expiry date', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + batch_number: 'BATCH-20260414-001', + production_date: null, + expiry_date: null, + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + }, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'PRODUCTION_DATE_REQUIRED'); + assert.match(result.message, /生产日期/); + assert.match(result.message, /有效期/); + assert.ok(Array.isArray(result.data.invalid_details)); + assert.equal(result.data.invalid_details[0].detail_id, 501); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should load batch-managed product data from query include before validating completion', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + system_product: null, + batch_number: 'BATCH-20260414-002', + production_date: null, + expiry_date: null, + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, + }, + hydrateSystemProductFromQuery: true, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'PRODUCTION_DATE_REQUIRED'); + assert.match(result.message, /生产日期/); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should reject completion when batch-managed product expires too soon for the minimum receiving days', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + batch_number: 'BATCH-20260414-003', + production_date: daysFromNow(-10), + expiry_date: daysFromNow(2), + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, + }, + }); + + const result = await service.completeReceiving({ id: 123 }); + + assert.equal(result.success, false); + assert.equal(result.code, 'EXPIRY_DATE_TOO_SOON'); + assert.match(result.message, /最小允许收货天数/); + assert.match(result.message, /无法完成收货/); + assert.ok(Array.isArray(result.data.invalid_details)); + assert.equal(result.data.invalid_details[0].detail_id, 501); + assert.equal(result.data.invalid_details[0].inbound_min_days, 3); + assert.deepEqual(steps, [ 'rollback' ]); + assert.equal(noticeCalls.length, 0); + }); + + it('should allow completion when batch-managed product has valid production and expiry dates', async () => { + const { service, steps, noticeCalls } = createCompleteReceivingService({ + detailOverrides: { + batch_number: 'BATCH-20260414-004', + production_date: daysFromNow(-10), + expiry_date: daysFromNow(30), + }, + systemProductOverrides: { + is_shelf_life_mgmt: 'Y', + is_batch_mgmt: 'Y', + inbound_min_days: 3, }, - itemImages: [], }); const result = await service.completeReceiving({ id: 123 }); @@ -575,7 +724,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(result.success, true); assert.deepEqual(steps, [ 'commit', 'notice:text', 'excel', 'notice:file' ]); assert.equal(noticeCalls.length, 2); - assert.equal(Number(result.data.stats.matched_details), 0); - assert.equal(Number(result.data.stats.unmatched_details), 1); + assert.equal(Number(result.data.stats.matched_details), 1); + assert.equal(Number(result.data.stats.unmatched_details), 0); }); }); diff --git a/test/support/order_service_test_helper.js b/test/support/order_service_test_helper.js new file mode 100644 index 0000000..b8e09ea --- /dev/null +++ b/test/support/order_service_test_helper.js @@ -0,0 +1,151 @@ +'use strict'; + +const Sequelize = require('sequelize'); + +function createServiceContext(storeId = 100000) { + return { + app: { + Sequelize, + config: {}, + }, + user: { + store_id: storeId, + }, + }; +} + +function buildRows(count, rowFactory = () => ({})) { + return Array.from({ length: count }, (_, index) => ({ + id: index + 1, + warehouse_id: 100000, + step: index % 2 === 0 ? 1 : 2, + dispatch_lane: 'm4', + inspection_status: 'fin', + updated_at: '2026-04-12 00:00:00', + ...rowFactory(index), + })); +} + +/** + * 判断模拟行数据是否匹配 where 条件。 + * @param {Object|Array|number|string|null} row 待匹配数据。 + * @param {Object} where Sequelize where 条件。 + * @return {boolean} 是否匹配。 + */ +function matchesWhere(row, where) { + if (!where || typeof where !== 'object') { + return true; + } + + const andConditions = where[Sequelize.Op.and]; + if (Array.isArray(andConditions)) { + return andConditions.every(condition => matchesWhere(row, condition)); + } + + const orConditions = where[Sequelize.Op.or]; + if (Array.isArray(orConditions)) { + return orConditions.some(condition => matchesWhere(row, condition)); + } + + return Object.entries(where).every(([ fieldName, condition ]) => { + if (condition && typeof condition === 'object' && !Array.isArray(condition)) { + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.eq)) { + return row[fieldName] === condition[Sequelize.Op.eq]; + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) { + return row[fieldName] !== condition[Sequelize.Op.ne]; + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.in)) { + const values = condition[Sequelize.Op.in]; + return Array.isArray(values) && values.includes(row[fieldName]); + } + + if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.notIn)) { + const values = condition[Sequelize.Op.notIn]; + return Array.isArray(values) && !values.includes(row[fieldName]); + } + + if (Object.keys(condition).length > 0 || Object.getOwnPropertySymbols(condition).length > 0) { + return matchesWhere(row[fieldName], condition); + } + } + + return row[fieldName] === condition; + }); +} + +/** + * 创建分页查询用的模拟模型。 + * @param {Array} rows 初始行数据。 + * @param {Object} capture 调用记录。 + * @return {Object} 模拟模型。 + */ +function createPagedMockModel(rows, capture = {}) { + const normalizedRows = Array.isArray(rows) ? rows.map(row => ({ ...row })) : []; + + return { + async count({ where } = {}) { + capture.countWhere = where; + return normalizedRows.filter(row => matchesWhere(row, where)).length; + }, + async findAll(options = {}) { + capture.findOptions = options; + + const filteredRows = normalizedRows.filter(row => matchesWhere(row, options.where)); + const offset = Number.parseInt(options.offset, 10) || 0; + const limitValue = options.limit === undefined ? filteredRows.length : Number.parseInt(options.limit, 10); + const limit = Number.isFinite(limitValue) ? Math.max(limitValue, 0) : filteredRows.length; + + return filteredRows.slice(offset, offset + limit).map(row => ({ ...row })); + }, + async update() { + return [ 1 ]; + }, + async findOne() { + const firstRow = normalizedRows[0]; + return firstRow ? { ...firstRow } : null; + }, + }; +} + +/** + * 创建订单服务测试环境。 + * @param {Function} ServiceClass 服务类构造器。 + * @param {Object} [options] 测试配置。 + * @return {{ ctx: Object, service: Object, captures: Array }} 测试上下文。 + */ +function createOrderHarness(ServiceClass, options = {}) { + const ctx = createServiceContext(options.storeId || 100000); + const service = new ServiceClass(ctx); + const captures = []; + const rowsByModule = options.rowsByModule || {}; + const defaultRows = Array.isArray(options.defaultRows) ? options.defaultRows : buildRows(1); + + service.getOrderModel = async moduleName => { + const capture = { + moduleName, + }; + captures.push(capture); + + const rows = Object.prototype.hasOwnProperty.call(rowsByModule, moduleName) + ? rowsByModule[moduleName] + : defaultRows; + + return createPagedMockModel(rows, capture); + }; + + return { + ctx, + service, + captures, + }; +} + +module.exports = { + buildRows, + createOrderHarness, + createServiceContext, + matchesWhere, +}; diff --git a/test/support/system_method_client.js b/test/support/system_method_client.js index 62a7bd1..44d94a7 100644 --- a/test/support/system_method_client.js +++ b/test/support/system_method_client.js @@ -1,8 +1,12 @@ 'use strict'; +const crypto = require('node:crypto'); const fs = require('node:fs'); const path = require('node:path'); const assert = require('node:assert/strict'); +const { XMLParser } = require('fast-xml-parser'); + +const loadDefaultConfig = require('../../config/config.default'); const BASE_URL = process.env.SYSTEM_TEST_BASE_URL || 'http://127.0.0.1:6060'; const BASE_GATEWAY_URL = process.env.SYSTEM_TEST_GATEWAY_BASE_URL || BASE_URL; @@ -11,10 +15,101 @@ const TOKEN_FILE = process.env.SYSTEM_TEST_TOKEN_FILE const USERNAME = process.env.SYSTEM_TEST_USERNAME || 'liufumingren'; const PASSWORD = process.env.SYSTEM_TEST_PASSWORD || '111111'; +const DEFAULT_APP_INFO = { + name: 'wms', + baseDir: process.cwd(), +}; + +let cachedQimenDefaults = null; + +function loadQimenDefaults() { + if (cachedQimenDefaults) { + return cachedQimenDefaults; + } + + try { + const defaultConfig = loadDefaultConfig(DEFAULT_APP_INFO) || {}; + cachedQimenDefaults = { + appKey: process.env.SYSTEM_TEST_QIMEN_APP_KEY || defaultConfig.qimen?.appKey || '', + secret: process.env.SYSTEM_TEST_QIMEN_SECRET || defaultConfig.qimen?.security || '', + }; + } catch { + cachedQimenDefaults = { + appKey: process.env.SYSTEM_TEST_QIMEN_APP_KEY || '', + secret: process.env.SYSTEM_TEST_QIMEN_SECRET || '', + }; + } + + return cachedQimenDefaults; +} + function nowSec() { return Math.floor(Date.now() / 1000); } +function normalizeString(value) { + return value === null || value === undefined ? '' : String(value); +} + +function buildTopSign(params, body, secret, signMethod = 'md5') { + const keys = Object.keys(params).sort(); + let query = ''; + const normalizedSignMethod = String(signMethod || '').toLowerCase(); + + if (normalizedSignMethod === 'md5') { + query += normalizeString(secret); + } + + for (const key of keys) { + const value = params[key]; + if (key && value) { + query += key + value; + } + } + + if (body) { + query += body; + } + + if (normalizedSignMethod === 'hmac') { + return crypto.createHmac('md5', normalizeString(secret)) + .update(query, 'utf8') + .digest('hex') + .toUpperCase(); + } + + if (normalizedSignMethod === 'hmac_sha256') { + return crypto.createHmac('sha256', normalizeString(secret)) + .update(query, 'utf8') + .digest('hex') + .toUpperCase(); + } + + query += normalizeString(secret); + return crypto.createHash('md5') + .update(query, 'utf8') + .digest('hex') + .toUpperCase(); +} + +function parseXmlBody(xmlText) { + try { + const parser = new XMLParser({ + ignoreAttributes: false, + attributeNamePrefix: '@_', + allowBooleanAttributes: true, + parseTagValue: false, + parseAttributeValue: false, + trimValues: false, + ignoreDeclaration: true, + }); + + return parser.parse(xmlText); + } catch { + return null; + } +} + function decodeJwtPayload(token) { try { const payloadSegment = token.split('.')[1]; @@ -97,6 +192,74 @@ async function invokeSystemMethod(method, body = {}, token, extra = {}) { }; } +/** + * 发送真实的 /qimen 请求,并返回原始响应文本。 + * @param {string} method 奇门方法名,例如 deliveryorder.create。 + * @param {string} xmlBody 原始 XML 请求体。 + * @param {Object} [options={}] 请求选项。 + * @param {string} [options.appKey] 请求 app_key;未传时读取 config.default.js 或环境变量覆盖值。 + * @param {string} [options.secret] 签名密钥;未传时读取 config.default.js 或环境变量覆盖值。 + * @param {string} [options.customerId] 客户编码。 + * @param {string} [options.timestamp] 时间戳;未传时使用当前秒级时间戳。 + * @param {string} [options.v='2.0'] 版本号。 + * @param {string} [options.format='xml'] 响应格式。 + * @param {string} [options.signMethod='md5'] 签名方式。 + * @param {string} [options.contentType='application/xml'] 请求 Content-Type。 + * @param {Object} [options.headers={}] 额外请求头。 + * @return {Promise<{status: number, body: string, parsed: Object|null, url: string, queryParams: Object}>} 请求结果。 + */ +async function invokeQimenMethod(method, xmlBody, options = {}) { + const qimenDefaults = loadQimenDefaults(); + const timestamp = options.timestamp || String(nowSec()); + const appKey = normalizeString(options.appKey || qimenDefaults.appKey); + const secret = normalizeString(options.secret || qimenDefaults.secret); + const customerId = normalizeString(options.customerId || ''); + const format = normalizeString(options.format || 'xml') || 'xml'; + const signMethod = normalizeString(options.signMethod || 'md5') || 'md5'; + const version = normalizeString(options.v || '2.0') || '2.0'; + const bodyText = normalizeString(xmlBody); + const queryParams = { + app_key: appKey, + method: normalizeString(method), + v: version, + format, + sign_method: signMethod, + timestamp, + }; + + if (customerId) { + queryParams.customerId = customerId; + } + + queryParams.sign = buildTopSign(queryParams, bodyText, secret, signMethod); + + const url = new URL(`${BASE_URL}/qimen`); + for (const [ key, value ] of Object.entries(queryParams)) { + if (value !== undefined && value !== null && value !== '') { + url.searchParams.set(key, value); + } + } + + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': options.contentType || 'application/xml', + ...(options.headers || {}), + }, + body: bodyText, + }); + + const text = await response.text(); + + return { + status: response.status, + body: text, + parsed: format.toLowerCase() === 'xml' ? parseXmlBody(text) : null, + url: url.toString(), + queryParams, + }; +} + async function getAuthToken(options = {}) { const { forceLogin = false } = options; @@ -160,6 +323,7 @@ module.exports = { TOKEN_FILE, USERNAME, invokeSystemMethod, + invokeQimenMethod, invokeGatewayMethod, getAuthToken, readCachedToken, diff --git a/test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md b/test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md new file mode 100644 index 0000000..7766184 --- /dev/null +++ b/test_reports/fail/20260412-1723-真实下单出库脚本验证报告.md @@ -0,0 +1,44 @@ +# 真实下单出库脚本验证报告 + +- 测试类型:接口验证,真实链路执行 +- 测试目标: + - 真实创建一笔订单 + - 通过内部出库服务完成 markOutboundOrder + - 确认脚本会把结果写到 temp 下的 JSON 文件,并打印同样内容 + - 回传执行结果,检查 createdOrderId、deliveryOrderCode、outboundResult、deliveryTime 是否有值,以及脚本是否退出码为 0 + +## 测试范围 + +- 执行脚本:[temp/trace-real-order-outbound.cjs](temp/trace-real-order-outbound.cjs) +- 结果文件:[temp/trace-real-order-outbound.json](temp/trace-real-order-outbound.json) +- 关联实现:[test/support/system_method_client.js](test/support/system_method_client.js) +- 关联服务:[app/service/systems/order_outbound.js](app/service/systems/order_outbound.js) + +## 测试产物 + +- 终端执行输出:脚本已实际运行并打印结果 JSON +- 结果 JSON 文件:已生成 [temp/trace-real-order-outbound.json](temp/trace-real-order-outbound.json) + +## 结果摘要 + +- createdOrderId:无值,结果为 0 +- deliveryOrderCode:有值,结果为 TRACE_OUTBOUND_1775985802028_F5254BAE +- outboundResult:无值,结果为 null +- deliveryTime:无值,结果为 null +- 脚本退出码:不是 0 + +## 关键失败点 + +- 脚本在执行到创建奇门订单前抛出断言错误,错误信息为:未找到可用库存用于创建奇门订单 +- 结果 JSON 中已经写入相同内容,说明脚本确实完成了结果落盘和控制台打印,但没有完成后续真实下单与 markOutboundOrder + +## 执行结论 + +- 本次执行失败,未完成完整的真实订单创建与内部出库链路 +- 最可能的根因是当前测试环境没有满足脚本所需的可用库存,导致在创建奇门订单阶段提前中断 + +## 建议 + +1. 先补齐脚本所需的可用库存,再重新执行同一脚本 +2. 如果库存是预期前置条件,建议在脚本开头增加更明确的前置检查和失败提示 +3. 如需继续定位,可重点检查脚本中创建奇门订单前的库存筛选逻辑,以及相关仓库和货主的可用库存状态 \ No newline at end of file diff --git a/test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md b/test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md new file mode 100644 index 0000000..7559c11 --- /dev/null +++ b/test_reports/fail/20260414-库存效期任务实例形态回归测试报告.md @@ -0,0 +1,38 @@ +# 库存效期任务实例形态回归测试报告 + +- 测试类型:单元测试 +- 测试目标:为 [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) 补充回归测试,验证 Storage.findAll 返回 Sequelize 实例风格对象时,任务仍能识别 stock_id / id / expiry_date / space 并发送通知、回写缓存。 + +## 测试范围 + +- [test/app/schedule/notice_stock_remaining.test.js](../../test/app/schedule/notice_stock_remaining.test.js) +- [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) + +## 测试产物 + +- 新增测试用例:普通对象路径 + Sequelize 实例形态路径 +- 测试命令:`npm run test:local -- test/app/schedule/notice_stock_remaining.test.js` + +## 测试结果摘要 + +- 普通对象用例:通过 +- 实例形态用例:失败 +- 失败数:1 +- 通过数:1 + +## 失败用例 + +- 用例名:`should read Sequelize instance-style rows via getDataValue/get and still send notice` +- 失败位置:[test/app/schedule/notice_stock_remaining.test.js](../../test/app/schedule/notice_stock_remaining.test.js#L254) +- 断言:`assert.equal(noticePayloads.length, 1)` +- 实际值:`noticePayloads.length === 0` + +## 失败原因 + +当前任务实现仍只通过自有属性读取字段。实例形态对象虽然提供了 `getDataValue/get`,但任务代码没有调用这些方法,因此 `stock_id/id/expiry_date/space` 没有被识别,通知未发送,缓存也未回写。 + +## 结论与建议 + +- 本次测试补强已覆盖普通对象路径,并新增了实例形态回归用例。 +- 由于业务代码未调整,实例形态用例仍然失败,当前问题未被修复。 +- 若要让该回归测试通过,需要在任务实现中补充对 Sequelize 实例的读取兼容,但本次按要求未修改业务代码。 diff --git a/test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md b/test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md new file mode 100644 index 0000000..8a5929d --- /dev/null +++ b/test_reports/pass/20260411-184847-order_delivery_dispatch_factory-MySQL建表集成测试报告.md @@ -0,0 +1,46 @@ +# order_delivery_dispatch_factory MySQL 建表集成测试报告 + +## 元信息 + +| 项 | 值 | +|----|-----| +| 测试类型 | 单元 + 集成(第三项依赖 MySQL + `DISPATCH_FACTORY_TEST_MYSQL=1`) | +| 执行时间 | 2026-04-11 | +| 范围 | `test/app/model/order_delivery_dispatch_factory.test.js` | + +## 测试目标 + +验证 `OrderDeliveryDispatchFactory` 的 M4/M5 分表命名、分区辅助逻辑;在显式开启 `egg-sequelize` 与可连 MySQL 时,验证首次 `getModel` 会创建物理表并命中缓存。 + +## 测试范围与产物 + +- 文件:`test/app/model/order_delivery_dispatch_factory.test.js` +- 配置:`config/plugin.js` 中 `sequelize.enable` 在 `NODE_ENV=test` 下仅当 `DISPATCH_FACTORY_TEST_MYSQL=1` 时启用 +- 快捷脚本:`npm run test:dispatch-factory`(需同时设置环境变量) + +## 测试结果摘要(带 MySQL 集成) + +**命令(PowerShell):** + +```text +$env:DISPATCH_FACTORY_TEST_MYSQL='1'; npm run test:local -- test/app/model/order_delivery_dispatch_factory.test.js +``` + +**结果:** 3 passing,0 failing,0 pending(第三项执行建表断言,非 skip)。 + +**说明:** 启动阶段可能出现 Sequelize 连接重试警告(如 `ETIMEDOUT` 后重试成功);Redis 在默认 test 下关闭属预期。 + +## 默认 test(不设环境变量) + +第三项在 `dialect() !== 'mysql'` 且未设置 `DISPATCH_FACTORY_TEST_MYSQL=1` 时 **skip**(Mocha 显示为 1 pending),前两例始终通过;适合不连库的 CI/本地快速跑。 + +**结果(本机复跑):** 2 passing,1 pending。 + +## 结论与建议 + +- 带 `DISPATCH_FACTORY_TEST_MYSQL=1` 时 M4/M5 建表路径已可真实断言;分区使用 `209901`、仓库 `100000`,与 `warehouse_shard_guard` 约定一致。 +- 建议在能连 `config` 中 wms MySQL 的流水线或本地定期执行带环境变量的单文件用例,无需跑全量 `test:local`。 + +## ESLint + +已对 `config/plugin.js`、`test/app/model/order_delivery_dispatch_factory.test.js` 执行 ESLint,无错误、无警告。 diff --git a/test_reports/pass/20260412-014727-订单工作台list单测报告.md b/test_reports/pass/20260412-014727-订单工作台list单测报告.md new file mode 100644 index 0000000..f700de1 --- /dev/null +++ b/test_reports/pass/20260412-014727-订单工作台list单测报告.md @@ -0,0 +1,53 @@ +# 订单工作台 list 单测报告 + +## 测试目标 + +补齐订单工作台 `list` 相关单测,覆盖 `app/service/systemMethods/order/base.js` 的 `buildWhere`、分页上限,以及订单命名空间各列表入口的返回结构与兼容旧入口。 + +## 测试类型 + +- 单元测试 +- 纯逻辑测试 +- 入口封装测试 + +## 测试范围 + +本次新增/修改的测试文件: + +- [test/support/order_service_test_helper.js](../../test/support/order_service_test_helper.js) +- [test/app/service/systemMethods/order.base.step.test.js](../../test/app/service/systemMethods/order.base.step.test.js) +- [test/app/controller/system.order.namespaced.test.js](../../test/app/controller/system.order.namespaced.test.js) +- [test/app/controller/system.order.reviewOrder.test.js](../../test/app/controller/system.order.reviewOrder.test.js) +- [test/app/controller/system.order.getreviewOrderlist.test.js](../../test/app/controller/system.order.getreviewOrderlist.test.js) + +## 覆盖点 + +- `buildWhere` + - `step = 1` 的等值过滤 + - `step.operator = in` 且 `value` 为数组的过滤 + - `warehouse_id` 注入确认 +- `listByModule` + - `pageSize` 超过上限时被截断到服务端限制值 + - `pagination.pageSize` 返回截断后的值 + - `list.length <= pagination.pageSize` + - `deliveryOrder` 场景下 `step` 条件可透传并过滤结果 +- 订单命名空间 list 入口 + - `order.list` 返回 `list/pagination` + - `pendingOrder`、`expectionOrder`、`entrustOrder`、`deliveryOrder`、`deliveryExpectionOrder`、`archiveOrder` 的 list 入口返回 `list/pagination` +- 兼容旧入口 + - `reviewOrder.list` 返回 `list/pagination` + - `getreviewOrderlist` 返回 `list/pagination` + +## 测试结果摘要 + +- 运行命令:`npx egg-bin test test/app/service/systemMethods/order.base.step.test.js test/app/controller/system.order.namespaced.test.js test/app/controller/system.order.reviewOrder.test.js test/app/controller/system.order.getreviewOrderlist.test.js` +- 结果:7 passing,0 failing +- 验证范围:覆盖纯 service 逻辑与订单命名空间入口返回结构,未依赖真实数据库数据 + +## 结论 + +本次订单工作台 `list` 相关单测已补齐,分页上限与 where 过滤链路已通过验证,且未修改业务代码和文档。 + +## 备注 + +测试用辅助工具已抽到 [test/support/order_service_test_helper.js](../../test/support/order_service_test_helper.js),便于后续继续补充同类订单入口测试。 diff --git a/test_reports/pass/20260412-165910-订单迁移回归测试报告.md b/test_reports/pass/20260412-165910-订单迁移回归测试报告.md new file mode 100644 index 0000000..82384c6 --- /dev/null +++ b/test_reports/pass/20260412-165910-订单迁移回归测试报告.md @@ -0,0 +1,35 @@ +# 订单迁移回归测试报告 + +- 测试类型:单元测试 + 静态检查 +- 测试目标:验证 `app/service/systems/order_delivery_migration.js` 在选中源行缺少 `delivery_order_code/store_id/warehouse_id` 时会 fail-fast 并回滚,同时正常迁移、批次上限和 item 迁移仍然正常。 +- 测试范围: + - `app/service/systems/order_delivery_migration.js` + - `test/app/service/systems/order_delivery_migration.test.js` + +## 测试产物 + +- 执行命令: + - `npm run test:local -- --grep "order_delivery_migration"` + - `npx eslint app/service/systems/order_delivery_migration.js test/app/service/systems/order_delivery_migration.test.js` +- 校验结果: + - `app/service/systems/order_delivery_migration.js` 无 ESLint/语法错误 + - `test/app/service/systems/order_delivery_migration.test.js` 无 ESLint/语法错误 + +## 测试结果摘要 + +- 单元测试:6 passing,0 failing,0 pending +- 静态检查:通过,退出码 `0` +- 关键回归场景: + - 缺少关键字段时立即抛错并回滚:通过 + - 正常迁移订单和商品明细:通过 + - 单批最多处理 1000 条:通过 + - 重复执行时跳过已迁移订单:通过 + +## 结论 + +本次订单迁移修复的回归验证通过。当前实现已满足 fail-fast + 回滚要求,且正常迁移、批次上限和 item 迁移路径未见回归。 + +## 备注 + +- 本次未发现失败用例。 +- 未执行全量 `npm run lint`,仅对目标文件做了针对性 ESLint 检查。 diff --git a/test_reports/pass/20260412-1753-真实收货入库流程验证报告.md b/test_reports/pass/20260412-1753-真实收货入库流程验证报告.md new file mode 100644 index 0000000..983e430 --- /dev/null +++ b/test_reports/pass/20260412-1753-真实收货入库流程验证报告.md @@ -0,0 +1,57 @@ +# 真实收货入库流程验证报告 + +- 测试类型:接口验证 / 集成验证 / 真实流程 smoke +- 执行日期:2026-04-12 +- 执行目标:完成一笔真实收货入库流程,确认收货单完成且库存确实增加 + +## 测试目标 + +1. 复用仓库现有真实流程脚本和系统方法客户端执行收货入库链路。 +2. 完成收货单创建、绑定货主、添加明细、绑定商品、完成收货、快捷入库。 +3. 验证库存前后变化,确认库存确实增加。 +4. 输出单据 ID、关键状态、库存变化证据。 + +## 测试范围 + +- [test/support/system_method_client.js](../../test/support/system_method_client.js) +- [temp/verify-receiving-flow-store100000.cjs](../../temp/verify-receiving-flow-store100000.cjs) +- [app/service/systems/storage/receiving.js](../../app/service/systems/storage/receiving.js) +- [app/service/systems/stock_store.js](../../app/service/systems/stock_store.js) + +## 测试产物 + +- 收货单 ID:697 +- 收货单号:R20555015 +- 入库单 ID:194 +- 入库单号:SCRK17759877887936252 +- 商品 ID:157059 +- 商品名称:yjm0411 +- 库存快照:before 31,after 34,delta +3 +- 收货状态:completed +- 收货入库状态:all +- 快捷入库明细数:1 +- 快捷入库返回状态:200 / 快捷入库完成 +- 报表 URL:已生成并可访问 + +## 测试结果摘要 + +- 收货单完成成功。 +- 快捷入库成功,返回入库单信息且 `entry_order.order_status = COMPLETED`。 +- 库存确实增加,`wms_stock_warehouse.quantity` 从 31 增加到 34,增量为 3。 +- `locked_quantity` 前后均为 0。 + +## 关键证据 + +- 快捷入库返回:`receiving_storage_status = all` +- 库存快照返回:`quantity: 31 -> 34` +- 入库单返回:`entry_order_code = SCRK17759877887936252` + +## 结论 + +本次真实收货入库流程成功,库存已实际增加,且收货单与入库单状态均符合预期。 + +## 备注 + +- 执行过程中曾出现一次失败,根因是明细先绑定商品后再执行 `detailChange`,导致 `system_product_id` 被清空,快捷入库被判定为“未匹配系统商品”。 +- 已按仓库现有测试顺序修正为先 `detailChange` 再 `bindDetailProduct`,最终执行通过。 +- 生成的 Excel 报表已可下载,但其预览内容中出现了旧的收货单编号片段;库存是否增加的最终判定以实时接口和数据库快照为准。 diff --git a/test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md b/test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md new file mode 100644 index 0000000..db84c4b --- /dev/null +++ b/test_reports/pass/20260414-库存效期任务跨天重发与旧缓存兼容验证报告.md @@ -0,0 +1,39 @@ +# 库存效期任务跨天重发与旧缓存兼容验证报告 + +- 测试类型:单元测试 + 只读临时脚本验证 +- 测试目标:复核 [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) 是否满足“每天都能再次提醒一次”的需求,并检查同日去重、跨天重发、商品间隔离、失败重试、旧缓存兼容。 + +## 测试范围 + +- [app/schedule/notice_stock_remaining.js](../../app/schedule/notice_stock_remaining.js) +- [test/app/schedule/notice_stock_remaining.test.js](../../test/app/schedule/notice_stock_remaining.test.js) + +## 测试产物 + +- 现有单测:4 passing,0 failing +- 临时只读验证:跨天重发与旧缓存对象格式兼容检查通过 +- ESLint:针对目标文件检查通过,退出码 0 + +## 结果摘要 + +1. 同一商品同一天内重复触发,只发送一次:通过 +2. 跨天后同一商品可以再次发送:通过 +3. 同一天内不同商品互不影响:通过 +4. 发送失败时不会写入去重缓存,下一轮仍会重试:通过 +5. 旧缓存格式兼容,不会误拦截新逻辑:通过 + +## 关键验证 + +- 现有单测覆盖了 legacy 全局缓存 key、同日商品级去重、失败不写缓存、`notice.index.send` 兼容路径。 +- 额外临时脚本验证了两个缺口: + - 同一商品跨天重跑时,会生成新的日粒度缓存键并再次发送。 + - legacy 缓存值为 JSON 字符串数组对象、以及对象 map 形态时,任务仍会正常发送,不会被旧缓存误拦截。 + +## 结论 + +当前实现已经满足“每天都能再次提醒一次”的目标,且没有发现同日去重、失败重试或旧缓存兼容方面的回归。 + +## 遗漏与风险 + +- 目前仓库内的正式单测已经覆盖了大部分核心路径,但跨天场景仍依赖本次临时只读脚本补强,建议后续补成正式单测,避免只靠手工验证。 +- 旧缓存兼容目前主要验证了旧缓存 key 与旧值形态不会阻断新逻辑;如果后续还会出现更复杂的历史缓存结构,建议再补一条专门回归用例。 diff --git a/worktrees/deploy-20260409155126 b/worktrees/deploy-20260409155126 deleted file mode 160000 index 69e992b..0000000 --- a/worktrees/deploy-20260409155126 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 69e992bf9dc1242f5c35b3aa5bdddcc716274045